<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">


<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    
    <title>Models &mdash; Django 1.7.8.dev20150401230226 documentation</title>
    
    <link rel="stylesheet" href="../../_static/default.css" type="text/css" />
    <link rel="stylesheet" href="../../_static/pygments.css" type="text/css" />
    
    <script type="text/javascript">
      var DOCUMENTATION_OPTIONS = {
        URL_ROOT:    '../../',
        VERSION:     '1.7.8.dev20150401230226',
        COLLAPSE_INDEX: false,
        FILE_SUFFIX: '.html',
        HAS_SOURCE:  true
      };
    </script>
    <script type="text/javascript" src="../../_static/jquery.js"></script>
    <script type="text/javascript" src="../../_static/underscore.js"></script>
    <script type="text/javascript" src="../../_static/doctools.js"></script>
    <link rel="top" title="Django 1.7.8.dev20150401230226 documentation" href="../../index.html" />
    <link rel="up" title="Models and databases" href="index.html" />
    <link rel="next" title="Making queries" href="queries.html" />
    <link rel="prev" title="Models and databases" href="index.html" />



 
<script type="text/javascript" src="../../templatebuiltins.js"></script>
<script type="text/javascript">
(function($) {
    if (!django_template_builtins) {
       // templatebuiltins.js missing, do nothing.
       return;
    }
    $(document).ready(function() {
        // Hyperlink Django template tags and filters
        var base = "../../ref/templates/builtins.html";
        if (base == "#") {
            // Special case for builtins.html itself
            base = "";
        }
        // Tags are keywords, class '.k'
        $("div.highlight\\-html\\+django span.k").each(function(i, elem) {
             var tagname = $(elem).text();
             if ($.inArray(tagname, django_template_builtins.ttags) != -1) {
                 var fragment = tagname.replace(/_/, '-');
                 $(elem).html("<a href='" + base + "#" + fragment + "'>" + tagname + "</a>");
             }
        });
        // Filters are functions, class '.nf'
        $("div.highlight\\-html\\+django span.nf").each(function(i, elem) {
             var filtername = $(elem).text();
             if ($.inArray(filtername, django_template_builtins.tfilters) != -1) {
                 var fragment = filtername.replace(/_/, '-');
                 $(elem).html("<a href='" + base + "#" + fragment + "'>" + filtername + "</a>");
             }
        });
    });
})(jQuery);
</script>


  </head>
  <body>

    <div class="document">
  <div id="custom-doc" class="yui-t6">
    <div id="hd">
      <h1><a href="../../index.html">Django 1.7.8.dev20150401230226 documentation</a></h1>
      <div id="global-nav">
        <a title="Home page" href="../../index.html">Home</a>  |
        <a title="Table of contents" href="../../contents.html">Table of contents</a>  |
        <a title="Global index" href="../../genindex.html">Index</a>  |
        <a title="Module index" href="../../py-modindex.html">Modules</a>
      </div>
      <div class="nav">
    &laquo; <a href="index.html" title="Models and databases">previous</a>
     |
    <a href="../index.html" title="Using Django" accesskey="U">up</a>
   |
    <a href="queries.html" title="Making queries">next</a> &raquo;</div>
    </div>

    <div id="bd">
      <div id="yui-main">
        <div class="yui-b">
          <div class="yui-g" id="topics-db-models">
            
  <div class="section" id="s-module-django.db.models">
<span id="s-models"></span><span id="module-django.db.models"></span><span id="models"></span><h1>Models<a class="headerlink" href="#module-django.db.models" title="Permalink to this headline">¶</a></h1>
<p>A model is the single, definitive source of information about your data. It
contains the essential fields and behaviors of the data you&#8217;re storing.
Generally, each model maps to a single database table.</p>
<p>The basics:</p>
<ul class="simple">
<li>Each model is a Python class that subclasses
<a class="reference internal" href="../../ref/models/instances.html#django.db.models.Model" title="django.db.models.Model"><tt class="xref py py-class docutils literal"><span class="pre">django.db.models.Model</span></tt></a>.</li>
<li>Each attribute of the model represents a database field.</li>
<li>With all of this, Django gives you an automatically-generated
database-access API; see <a class="reference internal" href="queries.html"><em>Making queries</em></a>.</li>
</ul>
<div class="section" id="s-quick-example">
<span id="quick-example"></span><h2>Quick example<a class="headerlink" href="#quick-example" title="Permalink to this headline">¶</a></h2>
<p>This example model defines a <tt class="docutils literal"><span class="pre">Person</span></tt>, which has a <tt class="docutils literal"><span class="pre">first_name</span></tt> and
<tt class="docutils literal"><span class="pre">last_name</span></tt>:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">from</span> <span class="nn">django.db</span> <span class="kn">import</span> <span class="n">models</span>

<span class="k">class</span> <span class="nc">Person</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span>
    <span class="n">first_name</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">CharField</span><span class="p">(</span><span class="n">max_length</span><span class="o">=</span><span class="mi">30</span><span class="p">)</span>
    <span class="n">last_name</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">CharField</span><span class="p">(</span><span class="n">max_length</span><span class="o">=</span><span class="mi">30</span><span class="p">)</span>
</pre></div>
</div>
<p><tt class="docutils literal"><span class="pre">first_name</span></tt> and <tt class="docutils literal"><span class="pre">last_name</span></tt> are <a class="reference internal" href="#fields">fields</a> of the model. Each field is
specified as a class attribute, and each attribute maps to a database column.</p>
<p>The above <tt class="docutils literal"><span class="pre">Person</span></tt> model would create a database table like this:</p>
<div class="highlight-sql"><div class="highlight"><pre><span class="k">CREATE</span> <span class="k">TABLE</span> <span class="n">myapp_person</span> <span class="p">(</span>
    <span class="ss">&quot;id&quot;</span> <span class="nb">serial</span> <span class="k">NOT</span> <span class="k">NULL</span> <span class="k">PRIMARY</span> <span class="k">KEY</span><span class="p">,</span>
    <span class="ss">&quot;first_name&quot;</span> <span class="nb">varchar</span><span class="p">(</span><span class="mi">30</span><span class="p">)</span> <span class="k">NOT</span> <span class="k">NULL</span><span class="p">,</span>
    <span class="ss">&quot;last_name&quot;</span> <span class="nb">varchar</span><span class="p">(</span><span class="mi">30</span><span class="p">)</span> <span class="k">NOT</span> <span class="k">NULL</span>
<span class="p">);</span>
</pre></div>
</div>
<p>Some technical notes:</p>
<ul class="simple">
<li>The name of the table, <tt class="docutils literal"><span class="pre">myapp_person</span></tt>, is automatically derived from
some model metadata but can be overridden. See <a class="reference internal" href="../../ref/models/options.html#table-names"><em>Table names</em></a> for more
details.</li>
<li>An <tt class="docutils literal"><span class="pre">id</span></tt> field is added automatically, but this behavior can be
overridden. See <a class="reference internal" href="#automatic-primary-key-fields"><em>Automatic primary key fields</em></a>.</li>
<li>The <tt class="docutils literal"><span class="pre">CREATE</span> <span class="pre">TABLE</span></tt> SQL in this example is formatted using PostgreSQL
syntax, but it&#8217;s worth noting Django uses SQL tailored to the database
backend specified in your <a class="reference internal" href="../settings.html"><em>settings file</em></a>.</li>
</ul>
</div>
<div class="section" id="s-using-models">
<span id="using-models"></span><h2>Using models<a class="headerlink" href="#using-models" title="Permalink to this headline">¶</a></h2>
<p>Once you have defined your models, you need to tell Django you&#8217;re going to <em>use</em>
those models. Do this by editing your settings file and changing the
<a class="reference internal" href="../../ref/settings.html#std:setting-INSTALLED_APPS"><tt class="xref std std-setting docutils literal"><span class="pre">INSTALLED_APPS</span></tt></a> setting to add the name of the module that contains
your <tt class="docutils literal"><span class="pre">models.py</span></tt>.</p>
<p>For example, if the models for your application live in the module
<tt class="docutils literal"><span class="pre">myapp.models</span></tt> (the package structure that is created for an
application by the <a class="reference internal" href="../../ref/django-admin.html#django-admin-startapp"><tt class="xref std std-djadmin docutils literal"><span class="pre">manage.py</span> <span class="pre">startapp</span></tt></a> script),
<a class="reference internal" href="../../ref/settings.html#std:setting-INSTALLED_APPS"><tt class="xref std std-setting docutils literal"><span class="pre">INSTALLED_APPS</span></tt></a> should read, in part:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">INSTALLED_APPS</span> <span class="o">=</span> <span class="p">(</span>
    <span class="c">#...</span>
    <span class="s">&#39;myapp&#39;</span><span class="p">,</span>
    <span class="c">#...</span>
<span class="p">)</span>
</pre></div>
</div>
<p>When you add new apps to <a class="reference internal" href="../../ref/settings.html#std:setting-INSTALLED_APPS"><tt class="xref std std-setting docutils literal"><span class="pre">INSTALLED_APPS</span></tt></a>, be sure to run
<a class="reference internal" href="../../ref/django-admin.html#django-admin-migrate"><tt class="xref std std-djadmin docutils literal"><span class="pre">manage.py</span> <span class="pre">migrate</span></tt></a>, optionally making migrations
for them first with <a class="reference internal" href="../../ref/django-admin.html#django-admin-makemigrations"><tt class="xref std std-djadmin docutils literal"><span class="pre">manage.py</span> <span class="pre">makemigrations</span></tt></a>.</p>
</div>
<div class="section" id="s-fields">
<span id="fields"></span><h2>Fields<a class="headerlink" href="#fields" title="Permalink to this headline">¶</a></h2>
<p>The most important part of a model &#8211; and the only required part of a model &#8211;
is the list of database fields it defines. Fields are specified by class
attributes. Be careful not to choose field names that conflict with the
<a class="reference internal" href="../../ref/models/instances.html"><em>models API</em></a> like <tt class="docutils literal"><span class="pre">clean</span></tt>, <tt class="docutils literal"><span class="pre">save</span></tt>, or
<tt class="docutils literal"><span class="pre">delete</span></tt>.</p>
<p>Example:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">from</span> <span class="nn">django.db</span> <span class="kn">import</span> <span class="n">models</span>

<span class="k">class</span> <span class="nc">Musician</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span>
    <span class="n">first_name</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">CharField</span><span class="p">(</span><span class="n">max_length</span><span class="o">=</span><span class="mi">50</span><span class="p">)</span>
    <span class="n">last_name</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">CharField</span><span class="p">(</span><span class="n">max_length</span><span class="o">=</span><span class="mi">50</span><span class="p">)</span>
    <span class="n">instrument</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">CharField</span><span class="p">(</span><span class="n">max_length</span><span class="o">=</span><span class="mi">100</span><span class="p">)</span>

<span class="k">class</span> <span class="nc">Album</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span>
    <span class="n">artist</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">ForeignKey</span><span class="p">(</span><span class="n">Musician</span><span class="p">)</span>
    <span class="n">name</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">CharField</span><span class="p">(</span><span class="n">max_length</span><span class="o">=</span><span class="mi">100</span><span class="p">)</span>
    <span class="n">release_date</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">DateField</span><span class="p">()</span>
    <span class="n">num_stars</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">IntegerField</span><span class="p">()</span>
</pre></div>
</div>
<div class="section" id="s-field-types">
<span id="field-types"></span><h3>Field types<a class="headerlink" href="#field-types" title="Permalink to this headline">¶</a></h3>
<p>Each field in your model should be an instance of the appropriate
<a class="reference internal" href="../../ref/models/fields.html#django.db.models.Field" title="django.db.models.Field"><tt class="xref py py-class docutils literal"><span class="pre">Field</span></tt></a> class. Django uses the field class types to
determine a few things:</p>
<ul class="simple">
<li>The database column type (e.g. <tt class="docutils literal"><span class="pre">INTEGER</span></tt>, <tt class="docutils literal"><span class="pre">VARCHAR</span></tt>).</li>
<li>The default HTML <a class="reference internal" href="../../ref/forms/widgets.html"><em>widget</em></a> to use when rendering a form
field (e.g. <tt class="docutils literal"><span class="pre">&lt;input</span> <span class="pre">type=&quot;text&quot;&gt;</span></tt>, <tt class="docutils literal"><span class="pre">&lt;select&gt;</span></tt>).</li>
<li>The minimal validation requirements, used in Django&#8217;s admin and in
automatically-generated forms.</li>
</ul>
<p>Django ships with dozens of built-in field types; you can find the complete list
in the <a class="reference internal" href="../../ref/models/fields.html#model-field-types"><em>model field reference</em></a>. You can easily write
your own fields if Django&#8217;s built-in ones don&#8217;t do the trick; see
<a class="reference internal" href="../../howto/custom-model-fields.html"><em>Writing custom model fields</em></a>.</p>
</div>
<div class="section" id="s-field-options">
<span id="field-options"></span><h3>Field options<a class="headerlink" href="#field-options" title="Permalink to this headline">¶</a></h3>
<p>Each field takes a certain set of field-specific arguments (documented in the
<a class="reference internal" href="../../ref/models/fields.html#model-field-types"><em>model field reference</em></a>). For example,
<a class="reference internal" href="../../ref/models/fields.html#django.db.models.CharField" title="django.db.models.CharField"><tt class="xref py py-class docutils literal"><span class="pre">CharField</span></tt></a> (and its subclasses) require a
<a class="reference internal" href="../../ref/models/fields.html#django.db.models.CharField.max_length" title="django.db.models.CharField.max_length"><tt class="xref py py-attr docutils literal"><span class="pre">max_length</span></tt></a> argument which specifies the size
of the <tt class="docutils literal"><span class="pre">VARCHAR</span></tt> database field used to store the data.</p>
<p>There&#8217;s also a set of common arguments available to all field types. All are
optional. They&#8217;re fully explained in the <a class="reference internal" href="../../ref/models/fields.html#common-model-field-options"><em>reference</em></a>, but here&#8217;s a quick summary of the most often-used
ones:</p>
<dl class="docutils">
<dt><a class="reference internal" href="../../ref/models/fields.html#django.db.models.Field.null" title="django.db.models.Field.null"><tt class="xref py py-attr docutils literal"><span class="pre">null</span></tt></a></dt>
<dd>If <tt class="docutils literal"><span class="pre">True</span></tt>, Django will store empty values as <tt class="docutils literal"><span class="pre">NULL</span></tt> in the database.
Default is <tt class="docutils literal"><span class="pre">False</span></tt>.</dd>
<dt><a class="reference internal" href="../../ref/models/fields.html#django.db.models.Field.blank" title="django.db.models.Field.blank"><tt class="xref py py-attr docutils literal"><span class="pre">blank</span></tt></a></dt>
<dd><p class="first">If <tt class="docutils literal"><span class="pre">True</span></tt>, the field is allowed to be blank. Default is <tt class="docutils literal"><span class="pre">False</span></tt>.</p>
<p class="last">Note that this is different than <a class="reference internal" href="../../ref/models/fields.html#django.db.models.Field.null" title="django.db.models.Field.null"><tt class="xref py py-attr docutils literal"><span class="pre">null</span></tt></a>.
<a class="reference internal" href="../../ref/models/fields.html#django.db.models.Field.null" title="django.db.models.Field.null"><tt class="xref py py-attr docutils literal"><span class="pre">null</span></tt></a> is purely database-related, whereas
<a class="reference internal" href="../../ref/models/fields.html#django.db.models.Field.blank" title="django.db.models.Field.blank"><tt class="xref py py-attr docutils literal"><span class="pre">blank</span></tt></a> is validation-related. If a field has
<a class="reference internal" href="../../ref/models/fields.html#django.db.models.Field.blank" title="django.db.models.Field.blank"><tt class="xref py py-attr docutils literal"><span class="pre">blank=True</span></tt></a>, form validation will
allow entry of an empty value. If a field has <a class="reference internal" href="../../ref/models/fields.html#django.db.models.Field.blank" title="django.db.models.Field.blank"><tt class="xref py py-attr docutils literal"><span class="pre">blank=False</span></tt></a>, the field will be required.</p>
</dd>
<dt><a class="reference internal" href="../../ref/models/fields.html#django.db.models.Field.choices" title="django.db.models.Field.choices"><tt class="xref py py-attr docutils literal"><span class="pre">choices</span></tt></a></dt>
<dd><p class="first">An iterable (e.g., a list or tuple) of 2-tuples to use as choices for
this field. If this is given, the default form widget will be a select box
instead of the standard text field and will limit choices to the choices
given.</p>
<p>A choices list looks like this:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">YEAR_IN_SCHOOL_CHOICES</span> <span class="o">=</span> <span class="p">(</span>
    <span class="p">(</span><span class="s">&#39;FR&#39;</span><span class="p">,</span> <span class="s">&#39;Freshman&#39;</span><span class="p">),</span>
    <span class="p">(</span><span class="s">&#39;SO&#39;</span><span class="p">,</span> <span class="s">&#39;Sophomore&#39;</span><span class="p">),</span>
    <span class="p">(</span><span class="s">&#39;JR&#39;</span><span class="p">,</span> <span class="s">&#39;Junior&#39;</span><span class="p">),</span>
    <span class="p">(</span><span class="s">&#39;SR&#39;</span><span class="p">,</span> <span class="s">&#39;Senior&#39;</span><span class="p">),</span>
    <span class="p">(</span><span class="s">&#39;GR&#39;</span><span class="p">,</span> <span class="s">&#39;Graduate&#39;</span><span class="p">),</span>
<span class="p">)</span>
</pre></div>
</div>
<p>The first element in each tuple is the value that will be stored in the
database, the second element will be displayed by the default form widget
or in a ModelChoiceField. Given an instance of a model object, the
display value for a choices field can be accessed using the
<tt class="docutils literal"><span class="pre">get_FOO_display</span></tt> method. For example:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">from</span> <span class="nn">django.db</span> <span class="kn">import</span> <span class="n">models</span>

<span class="k">class</span> <span class="nc">Person</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span>
    <span class="n">SHIRT_SIZES</span> <span class="o">=</span> <span class="p">(</span>
        <span class="p">(</span><span class="s">&#39;S&#39;</span><span class="p">,</span> <span class="s">&#39;Small&#39;</span><span class="p">),</span>
        <span class="p">(</span><span class="s">&#39;M&#39;</span><span class="p">,</span> <span class="s">&#39;Medium&#39;</span><span class="p">),</span>
        <span class="p">(</span><span class="s">&#39;L&#39;</span><span class="p">,</span> <span class="s">&#39;Large&#39;</span><span class="p">),</span>
    <span class="p">)</span>
    <span class="n">name</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">CharField</span><span class="p">(</span><span class="n">max_length</span><span class="o">=</span><span class="mi">60</span><span class="p">)</span>
    <span class="n">shirt_size</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">CharField</span><span class="p">(</span><span class="n">max_length</span><span class="o">=</span><span class="mi">1</span><span class="p">,</span> <span class="n">choices</span><span class="o">=</span><span class="n">SHIRT_SIZES</span><span class="p">)</span>
</pre></div>
</div>
<div class="last highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">p</span> <span class="o">=</span> <span class="n">Person</span><span class="p">(</span><span class="n">name</span><span class="o">=</span><span class="s">&quot;Fred Flintstone&quot;</span><span class="p">,</span> <span class="n">shirt_size</span><span class="o">=</span><span class="s">&quot;L&quot;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">p</span><span class="o">.</span><span class="n">save</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">p</span><span class="o">.</span><span class="n">shirt_size</span>
<span class="go">u&#39;L&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">p</span><span class="o">.</span><span class="n">get_shirt_size_display</span><span class="p">()</span>
<span class="go">u&#39;Large&#39;</span>
</pre></div>
</div>
</dd>
<dt><a class="reference internal" href="../../ref/models/fields.html#django.db.models.Field.default" title="django.db.models.Field.default"><tt class="xref py py-attr docutils literal"><span class="pre">default</span></tt></a></dt>
<dd>The default value for the field. This can be a value or a callable
object. If callable it will be called every time a new object is
created.</dd>
<dt><a class="reference internal" href="../../ref/models/fields.html#django.db.models.Field.help_text" title="django.db.models.Field.help_text"><tt class="xref py py-attr docutils literal"><span class="pre">help_text</span></tt></a></dt>
<dd>Extra &#8220;help&#8221; text to be displayed with the form widget. It&#8217;s useful for
documentation even if your field isn&#8217;t used on a form.</dd>
<dt><a class="reference internal" href="../../ref/models/fields.html#django.db.models.Field.primary_key" title="django.db.models.Field.primary_key"><tt class="xref py py-attr docutils literal"><span class="pre">primary_key</span></tt></a></dt>
<dd><p class="first">If <tt class="docutils literal"><span class="pre">True</span></tt>, this field is the primary key for the model.</p>
<p>If you don&#8217;t specify <a class="reference internal" href="../../ref/models/fields.html#django.db.models.Field.primary_key" title="django.db.models.Field.primary_key"><tt class="xref py py-attr docutils literal"><span class="pre">primary_key=True</span></tt></a> for
any fields in your model, Django will automatically add an
<a class="reference internal" href="../../ref/models/fields.html#django.db.models.IntegerField" title="django.db.models.IntegerField"><tt class="xref py py-class docutils literal"><span class="pre">IntegerField</span></tt></a> to hold the primary key, so you don&#8217;t need to set
<a class="reference internal" href="../../ref/models/fields.html#django.db.models.Field.primary_key" title="django.db.models.Field.primary_key"><tt class="xref py py-attr docutils literal"><span class="pre">primary_key=True</span></tt></a> on any of your fields
unless you want to override the default primary-key behavior. For more,
see <a class="reference internal" href="#automatic-primary-key-fields"><em>Automatic primary key fields</em></a>.</p>
<p>The primary key field is read-only. If you change the value of the primary
key on an existing object and then save it, a new object will be created
alongside the old one. For example:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">from</span> <span class="nn">django.db</span> <span class="kn">import</span> <span class="n">models</span>

<span class="k">class</span> <span class="nc">Fruit</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span>
    <span class="n">name</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">CharField</span><span class="p">(</span><span class="n">max_length</span><span class="o">=</span><span class="mi">100</span><span class="p">,</span> <span class="n">primary_key</span><span class="o">=</span><span class="bp">True</span><span class="p">)</span>
</pre></div>
</div>
<div class="last highlight-pycon"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">fruit</span> <span class="o">=</span> <span class="n">Fruit</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">create</span><span class="p">(</span><span class="n">name</span><span class="o">=</span><span class="s">&#39;Apple&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">fruit</span><span class="o">.</span><span class="n">name</span> <span class="o">=</span> <span class="s">&#39;Pear&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">fruit</span><span class="o">.</span><span class="n">save</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Fruit</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">values_list</span><span class="p">(</span><span class="s">&#39;name&#39;</span><span class="p">,</span> <span class="n">flat</span><span class="o">=</span><span class="bp">True</span><span class="p">)</span>
<span class="go">[&#39;Apple&#39;, &#39;Pear&#39;]</span>
</pre></div>
</div>
</dd>
<dt><a class="reference internal" href="../../ref/models/fields.html#django.db.models.Field.unique" title="django.db.models.Field.unique"><tt class="xref py py-attr docutils literal"><span class="pre">unique</span></tt></a></dt>
<dd>If <tt class="docutils literal"><span class="pre">True</span></tt>, this field must be unique throughout the table.</dd>
</dl>
<p>Again, these are just short descriptions of the most common field options. Full
details can be found in the <a class="reference internal" href="../../ref/models/fields.html#common-model-field-options"><em>common model field option reference</em></a>.</p>
</div>
<div class="section" id="s-automatic-primary-key-fields">
<span id="s-id1"></span><span id="automatic-primary-key-fields"></span><span id="id1"></span><h3>Automatic primary key fields<a class="headerlink" href="#automatic-primary-key-fields" title="Permalink to this headline">¶</a></h3>
<p>By default, Django gives each model the following field:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="nb">id</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">AutoField</span><span class="p">(</span><span class="n">primary_key</span><span class="o">=</span><span class="bp">True</span><span class="p">)</span>
</pre></div>
</div>
<p>This is an auto-incrementing primary key.</p>
<p>If you&#8217;d like to specify a custom primary key, just specify
<a class="reference internal" href="../../ref/models/fields.html#django.db.models.Field.primary_key" title="django.db.models.Field.primary_key"><tt class="xref py py-attr docutils literal"><span class="pre">primary_key=True</span></tt></a> on one of your fields. If Django
sees you&#8217;ve explicitly set <a class="reference internal" href="../../ref/models/fields.html#django.db.models.Field.primary_key" title="django.db.models.Field.primary_key"><tt class="xref py py-attr docutils literal"><span class="pre">Field.primary_key</span></tt></a>, it won&#8217;t add the automatic
<tt class="docutils literal"><span class="pre">id</span></tt> column.</p>
<p>Each model requires exactly one field to have <a class="reference internal" href="../../ref/models/fields.html#django.db.models.Field.primary_key" title="django.db.models.Field.primary_key"><tt class="xref py py-attr docutils literal"><span class="pre">primary_key=True</span></tt></a> (either explicitly declared or automatically added).</p>
</div>
<div class="section" id="s-verbose-field-names">
<span id="s-id2"></span><span id="verbose-field-names"></span><span id="id2"></span><h3>Verbose field names<a class="headerlink" href="#verbose-field-names" title="Permalink to this headline">¶</a></h3>
<p>Each field type, except for <a class="reference internal" href="../../ref/models/fields.html#django.db.models.ForeignKey" title="django.db.models.ForeignKey"><tt class="xref py py-class docutils literal"><span class="pre">ForeignKey</span></tt></a>,
<a class="reference internal" href="../../ref/models/fields.html#django.db.models.ManyToManyField" title="django.db.models.ManyToManyField"><tt class="xref py py-class docutils literal"><span class="pre">ManyToManyField</span></tt></a> and
<a class="reference internal" href="../../ref/models/fields.html#django.db.models.OneToOneField" title="django.db.models.OneToOneField"><tt class="xref py py-class docutils literal"><span class="pre">OneToOneField</span></tt></a>, takes an optional first positional
argument &#8211; a verbose name. If the verbose name isn&#8217;t given, Django will
automatically create it using the field&#8217;s attribute name, converting underscores
to spaces.</p>
<p>In this example, the verbose name is <tt class="docutils literal"><span class="pre">&quot;person's</span> <span class="pre">first</span> <span class="pre">name&quot;</span></tt>:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">first_name</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">CharField</span><span class="p">(</span><span class="s">&quot;person&#39;s first name&quot;</span><span class="p">,</span> <span class="n">max_length</span><span class="o">=</span><span class="mi">30</span><span class="p">)</span>
</pre></div>
</div>
<p>In this example, the verbose name is <tt class="docutils literal"><span class="pre">&quot;first</span> <span class="pre">name&quot;</span></tt>:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">first_name</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">CharField</span><span class="p">(</span><span class="n">max_length</span><span class="o">=</span><span class="mi">30</span><span class="p">)</span>
</pre></div>
</div>
<p><a class="reference internal" href="../../ref/models/fields.html#django.db.models.ForeignKey" title="django.db.models.ForeignKey"><tt class="xref py py-class docutils literal"><span class="pre">ForeignKey</span></tt></a>,
<a class="reference internal" href="../../ref/models/fields.html#django.db.models.ManyToManyField" title="django.db.models.ManyToManyField"><tt class="xref py py-class docutils literal"><span class="pre">ManyToManyField</span></tt></a> and
<a class="reference internal" href="../../ref/models/fields.html#django.db.models.OneToOneField" title="django.db.models.OneToOneField"><tt class="xref py py-class docutils literal"><span class="pre">OneToOneField</span></tt></a> require the first argument to be a
model class, so use the <a class="reference internal" href="../../ref/models/fields.html#django.db.models.Field.verbose_name" title="django.db.models.Field.verbose_name"><tt class="xref py py-attr docutils literal"><span class="pre">verbose_name</span></tt></a> keyword argument:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">poll</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">ForeignKey</span><span class="p">(</span><span class="n">Poll</span><span class="p">,</span> <span class="n">verbose_name</span><span class="o">=</span><span class="s">&quot;the related poll&quot;</span><span class="p">)</span>
<span class="n">sites</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">ManyToManyField</span><span class="p">(</span><span class="n">Site</span><span class="p">,</span> <span class="n">verbose_name</span><span class="o">=</span><span class="s">&quot;list of sites&quot;</span><span class="p">)</span>
<span class="n">place</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">OneToOneField</span><span class="p">(</span><span class="n">Place</span><span class="p">,</span> <span class="n">verbose_name</span><span class="o">=</span><span class="s">&quot;related place&quot;</span><span class="p">)</span>
</pre></div>
</div>
<p>The convention is not to capitalize the first letter of the
<a class="reference internal" href="../../ref/models/fields.html#django.db.models.Field.verbose_name" title="django.db.models.Field.verbose_name"><tt class="xref py py-attr docutils literal"><span class="pre">verbose_name</span></tt></a>. Django will automatically capitalize the first
letter where it needs to.</p>
</div>
<div class="section" id="s-relationships">
<span id="relationships"></span><h3>Relationships<a class="headerlink" href="#relationships" title="Permalink to this headline">¶</a></h3>
<p>Clearly, the power of relational databases lies in relating tables to each
other. Django offers ways to define the three most common types of database
relationships: many-to-one, many-to-many and one-to-one.</p>
<div class="section" id="s-many-to-one-relationships">
<span id="many-to-one-relationships"></span><h4>Many-to-one relationships<a class="headerlink" href="#many-to-one-relationships" title="Permalink to this headline">¶</a></h4>
<p>To define a many-to-one relationship, use <a class="reference internal" href="../../ref/models/fields.html#django.db.models.ForeignKey" title="django.db.models.ForeignKey"><tt class="xref py py-class docutils literal"><span class="pre">django.db.models.ForeignKey</span></tt></a>.
You use it just like any other <a class="reference internal" href="../../ref/models/fields.html#django.db.models.Field" title="django.db.models.Field"><tt class="xref py py-class docutils literal"><span class="pre">Field</span></tt></a> type: by
including it as a class attribute of your model.</p>
<p><a class="reference internal" href="../../ref/models/fields.html#django.db.models.ForeignKey" title="django.db.models.ForeignKey"><tt class="xref py py-class docutils literal"><span class="pre">ForeignKey</span></tt></a> requires a positional argument: the class
to which the model is related.</p>
<p>For example, if a <tt class="docutils literal"><span class="pre">Car</span></tt> model has a <tt class="docutils literal"><span class="pre">Manufacturer</span></tt> &#8211; that is, a
<tt class="docutils literal"><span class="pre">Manufacturer</span></tt> makes multiple cars but each <tt class="docutils literal"><span class="pre">Car</span></tt> only has one
<tt class="docutils literal"><span class="pre">Manufacturer</span></tt> &#8211; use the following definitions:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">from</span> <span class="nn">django.db</span> <span class="kn">import</span> <span class="n">models</span>

<span class="k">class</span> <span class="nc">Manufacturer</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span>
    <span class="c"># ...</span>
    <span class="k">pass</span>

<span class="k">class</span> <span class="nc">Car</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span>
    <span class="n">manufacturer</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">ForeignKey</span><span class="p">(</span><span class="n">Manufacturer</span><span class="p">)</span>
    <span class="c"># ...</span>
</pre></div>
</div>
<p>You can also create <a class="reference internal" href="../../ref/models/fields.html#recursive-relationships"><em>recursive relationships</em></a> (an
object with a many-to-one relationship to itself) and <a class="reference internal" href="../../ref/models/fields.html#lazy-relationships"><em>relationships to
models not yet defined</em></a>; see <a class="reference internal" href="../../ref/models/fields.html#ref-foreignkey"><em>the model field
reference</em></a> for details.</p>
<p>It&#8217;s suggested, but not required, that the name of a
<a class="reference internal" href="../../ref/models/fields.html#django.db.models.ForeignKey" title="django.db.models.ForeignKey"><tt class="xref py py-class docutils literal"><span class="pre">ForeignKey</span></tt></a> field (<tt class="docutils literal"><span class="pre">manufacturer</span></tt> in the example
above) be the name of the model, lowercase. You can, of course, call the field
whatever you want. For example:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">class</span> <span class="nc">Car</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span>
    <span class="n">company_that_makes_it</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">ForeignKey</span><span class="p">(</span><span class="n">Manufacturer</span><span class="p">)</span>
    <span class="c"># ...</span>
</pre></div>
</div>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<p><a class="reference internal" href="../../ref/models/fields.html#django.db.models.ForeignKey" title="django.db.models.ForeignKey"><tt class="xref py py-class docutils literal"><span class="pre">ForeignKey</span></tt></a> fields accept a number of extra
arguments which are explained in <a class="reference internal" href="../../ref/models/fields.html#foreign-key-arguments"><em>the model field reference</em></a>. These options help define how the relationship
should work; all are optional.</p>
<p>For details on accessing backwards-related objects, see the
<a class="reference internal" href="queries.html#backwards-related-objects"><em>Following relationships backward example</em></a>.</p>
<p class="last">For sample code, see the <a class="reference internal" href="examples/many_to_one.html"><em>Many-to-one relationship model example</em></a>.</p>
</div>
</div>
<div class="section" id="s-many-to-many-relationships">
<span id="many-to-many-relationships"></span><h4>Many-to-many relationships<a class="headerlink" href="#many-to-many-relationships" title="Permalink to this headline">¶</a></h4>
<p>To define a many-to-many relationship, use
<a class="reference internal" href="../../ref/models/fields.html#django.db.models.ManyToManyField" title="django.db.models.ManyToManyField"><tt class="xref py py-class docutils literal"><span class="pre">ManyToManyField</span></tt></a>. You use it just like any other
<a class="reference internal" href="../../ref/models/fields.html#django.db.models.Field" title="django.db.models.Field"><tt class="xref py py-class docutils literal"><span class="pre">Field</span></tt></a> type: by including it as a class attribute of
your model.</p>
<p><a class="reference internal" href="../../ref/models/fields.html#django.db.models.ManyToManyField" title="django.db.models.ManyToManyField"><tt class="xref py py-class docutils literal"><span class="pre">ManyToManyField</span></tt></a> requires a positional argument: the
class to which the model is related.</p>
<p>For example, if a <tt class="docutils literal"><span class="pre">Pizza</span></tt> has multiple <tt class="docutils literal"><span class="pre">Topping</span></tt> objects &#8211; that is, a
<tt class="docutils literal"><span class="pre">Topping</span></tt> can be on multiple pizzas and each <tt class="docutils literal"><span class="pre">Pizza</span></tt> has multiple toppings
&#8211; here&#8217;s how you&#8217;d represent that:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">from</span> <span class="nn">django.db</span> <span class="kn">import</span> <span class="n">models</span>

<span class="k">class</span> <span class="nc">Topping</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span>
    <span class="c"># ...</span>
    <span class="k">pass</span>

<span class="k">class</span> <span class="nc">Pizza</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span>
    <span class="c"># ...</span>
    <span class="n">toppings</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">ManyToManyField</span><span class="p">(</span><span class="n">Topping</span><span class="p">)</span>
</pre></div>
</div>
<p>As with <a class="reference internal" href="../../ref/models/fields.html#django.db.models.ForeignKey" title="django.db.models.ForeignKey"><tt class="xref py py-class docutils literal"><span class="pre">ForeignKey</span></tt></a>, you can also create
<a class="reference internal" href="../../ref/models/fields.html#recursive-relationships"><em>recursive relationships</em></a> (an object with a
many-to-many relationship to itself) and <a class="reference internal" href="../../ref/models/fields.html#lazy-relationships"><em>relationships to models not yet
defined</em></a>; see <a class="reference internal" href="../../ref/models/fields.html#ref-manytomany"><em>the model field reference</em></a> for details.</p>
<p>It&#8217;s suggested, but not required, that the name of a
<a class="reference internal" href="../../ref/models/fields.html#django.db.models.ManyToManyField" title="django.db.models.ManyToManyField"><tt class="xref py py-class docutils literal"><span class="pre">ManyToManyField</span></tt></a> (<tt class="docutils literal"><span class="pre">toppings</span></tt> in the example above)
be a plural describing the set of related model objects.</p>
<p>It doesn&#8217;t matter which model has the
<a class="reference internal" href="../../ref/models/fields.html#django.db.models.ManyToManyField" title="django.db.models.ManyToManyField"><tt class="xref py py-class docutils literal"><span class="pre">ManyToManyField</span></tt></a>, but you should only put it in one
of the models &#8211; not both.</p>
<p>Generally, <a class="reference internal" href="../../ref/models/fields.html#django.db.models.ManyToManyField" title="django.db.models.ManyToManyField"><tt class="xref py py-class docutils literal"><span class="pre">ManyToManyField</span></tt></a> instances should go in
the object that&#8217;s going to be edited on a form. In the above example,
<tt class="docutils literal"><span class="pre">toppings</span></tt> is in <tt class="docutils literal"><span class="pre">Pizza</span></tt> (rather than <tt class="docutils literal"><span class="pre">Topping</span></tt> having a <tt class="docutils literal"><span class="pre">pizzas</span></tt>
<a class="reference internal" href="../../ref/models/fields.html#django.db.models.ManyToManyField" title="django.db.models.ManyToManyField"><tt class="xref py py-class docutils literal"><span class="pre">ManyToManyField</span></tt></a> ) because it&#8217;s more natural to think
about a pizza having toppings than a topping being on multiple pizzas. The way
it&#8217;s set up above, the <tt class="docutils literal"><span class="pre">Pizza</span></tt> form would let users select the toppings.</p>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<p class="last">See the <a class="reference internal" href="examples/many_to_many.html"><em>Many-to-many relationship model example</em></a> for a full example.</p>
</div>
<p><a class="reference internal" href="../../ref/models/fields.html#django.db.models.ManyToManyField" title="django.db.models.ManyToManyField"><tt class="xref py py-class docutils literal"><span class="pre">ManyToManyField</span></tt></a> fields also accept a number of
extra arguments which are explained in <a class="reference internal" href="../../ref/models/fields.html#manytomany-arguments"><em>the model field reference</em></a>. These options help define how the relationship
should work; all are optional.</p>
</div>
<div class="section" id="s-extra-fields-on-many-to-many-relationships">
<span id="s-intermediary-manytomany"></span><span id="extra-fields-on-many-to-many-relationships"></span><span id="intermediary-manytomany"></span><h4>Extra fields on many-to-many relationships<a class="headerlink" href="#extra-fields-on-many-to-many-relationships" title="Permalink to this headline">¶</a></h4>
<p>When you&#8217;re only dealing with simple many-to-many relationships such as
mixing and matching pizzas and toppings, a standard
<a class="reference internal" href="../../ref/models/fields.html#django.db.models.ManyToManyField" title="django.db.models.ManyToManyField"><tt class="xref py py-class docutils literal"><span class="pre">ManyToManyField</span></tt></a> is all you need. However, sometimes
you may need to associate data with the relationship between two models.</p>
<p>For example, consider the case of an application tracking the musical groups
which musicians belong to. There is a many-to-many relationship between a person
and the groups of which they are a member, so you could use a
<a class="reference internal" href="../../ref/models/fields.html#django.db.models.ManyToManyField" title="django.db.models.ManyToManyField"><tt class="xref py py-class docutils literal"><span class="pre">ManyToManyField</span></tt></a> to represent this relationship.
However, there is a lot of detail about the membership that you might want to
collect, such as the date at which the person joined the group.</p>
<p>For these situations, Django allows you to specify the model that will be used
to govern the many-to-many relationship. You can then put extra fields on the
intermediate model. The intermediate model is associated with the
<a class="reference internal" href="../../ref/models/fields.html#django.db.models.ManyToManyField" title="django.db.models.ManyToManyField"><tt class="xref py py-class docutils literal"><span class="pre">ManyToManyField</span></tt></a> using the
<a class="reference internal" href="../../ref/models/fields.html#django.db.models.ManyToManyField.through" title="django.db.models.ManyToManyField.through"><tt class="xref py py-attr docutils literal"><span class="pre">through</span></tt></a> argument to point to the model
that will act as an intermediary. For our musician example, the code would look
something like this:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">from</span> <span class="nn">django.db</span> <span class="kn">import</span> <span class="n">models</span>

<span class="k">class</span> <span class="nc">Person</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span>
    <span class="n">name</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">CharField</span><span class="p">(</span><span class="n">max_length</span><span class="o">=</span><span class="mi">128</span><span class="p">)</span>

    <span class="k">def</span> <span class="nf">__str__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>              <span class="c"># __unicode__ on Python 2</span>
        <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">name</span>

<span class="k">class</span> <span class="nc">Group</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span>
    <span class="n">name</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">CharField</span><span class="p">(</span><span class="n">max_length</span><span class="o">=</span><span class="mi">128</span><span class="p">)</span>
    <span class="n">members</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">ManyToManyField</span><span class="p">(</span><span class="n">Person</span><span class="p">,</span> <span class="n">through</span><span class="o">=</span><span class="s">&#39;Membership&#39;</span><span class="p">)</span>

    <span class="k">def</span> <span class="nf">__str__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>              <span class="c"># __unicode__ on Python 2</span>
        <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">name</span>

<span class="k">class</span> <span class="nc">Membership</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span>
    <span class="n">person</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">ForeignKey</span><span class="p">(</span><span class="n">Person</span><span class="p">)</span>
    <span class="n">group</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">ForeignKey</span><span class="p">(</span><span class="n">Group</span><span class="p">)</span>
    <span class="n">date_joined</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">DateField</span><span class="p">()</span>
    <span class="n">invite_reason</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">CharField</span><span class="p">(</span><span class="n">max_length</span><span class="o">=</span><span class="mi">64</span><span class="p">)</span>
</pre></div>
</div>
<p>When you set up the intermediary model, you explicitly specify foreign
keys to the models that are involved in the many-to-many relationship. This
explicit declaration defines how the two models are related.</p>
<p>There are a few restrictions on the intermediate model:</p>
<ul class="simple">
<li>Your intermediate model must contain one - and <em>only</em> one - foreign key
to the source model (this would be <tt class="docutils literal"><span class="pre">Group</span></tt> in our example), or you must
explicitly specify the foreign keys Django should use for the relationship
using <a class="reference internal" href="../../ref/models/fields.html#django.db.models.ManyToManyField.through_fields" title="django.db.models.ManyToManyField.through_fields"><tt class="xref py py-attr docutils literal"><span class="pre">ManyToManyField.through_fields</span></tt></a>.
If you have more than one foreign key and <tt class="docutils literal"><span class="pre">through_fields</span></tt> is not
specified, a validation error will be raised. A similar restriction applies
to the foreign key to the target model (this would be <tt class="docutils literal"><span class="pre">Person</span></tt> in our
example).</li>
<li>For a model which has a many-to-many relationship to itself through an
intermediary model, two foreign keys to the same model are permitted, but
they will be treated as the two (different) sides of the many-to-many
relationship. If there are <em>more</em> than two foreign keys though, you
must also specify <tt class="docutils literal"><span class="pre">through_fields</span></tt> as above, or a validation error
will be raised.</li>
<li>When defining a many-to-many relationship from a model to
itself, using an intermediary model, you <em>must</em> use
<a class="reference internal" href="../../ref/models/fields.html#django.db.models.ManyToManyField.symmetrical" title="django.db.models.ManyToManyField.symmetrical"><tt class="xref py py-attr docutils literal"><span class="pre">symmetrical=False</span></tt></a> (see
<a class="reference internal" href="../../ref/models/fields.html#manytomany-arguments"><em>the model field reference</em></a>).</li>
</ul>
<div class="versionchanged">
<span class="title">Changed in Django 1.7:</span> <p>In Django 1.6 and earlier, intermediate models containing more than one
foreign key to any of the models involved in the many-to-many relationship
used to be prohibited.</p>
</div>
<p>Now that you have set up your <a class="reference internal" href="../../ref/models/fields.html#django.db.models.ManyToManyField" title="django.db.models.ManyToManyField"><tt class="xref py py-class docutils literal"><span class="pre">ManyToManyField</span></tt></a> to use
your intermediary model (<tt class="docutils literal"><span class="pre">Membership</span></tt>, in this case), you&#8217;re ready to start
creating some many-to-many relationships. You do this by creating instances of
the intermediate model:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">ringo</span> <span class="o">=</span> <span class="n">Person</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">create</span><span class="p">(</span><span class="n">name</span><span class="o">=</span><span class="s">&quot;Ringo Starr&quot;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">paul</span> <span class="o">=</span> <span class="n">Person</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">create</span><span class="p">(</span><span class="n">name</span><span class="o">=</span><span class="s">&quot;Paul McCartney&quot;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">beatles</span> <span class="o">=</span> <span class="n">Group</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">create</span><span class="p">(</span><span class="n">name</span><span class="o">=</span><span class="s">&quot;The Beatles&quot;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">m1</span> <span class="o">=</span> <span class="n">Membership</span><span class="p">(</span><span class="n">person</span><span class="o">=</span><span class="n">ringo</span><span class="p">,</span> <span class="n">group</span><span class="o">=</span><span class="n">beatles</span><span class="p">,</span>
<span class="gp">... </span>    <span class="n">date_joined</span><span class="o">=</span><span class="n">date</span><span class="p">(</span><span class="mi">1962</span><span class="p">,</span> <span class="mi">8</span><span class="p">,</span> <span class="mi">16</span><span class="p">),</span>
<span class="gp">... </span>    <span class="n">invite_reason</span><span class="o">=</span><span class="s">&quot;Needed a new drummer.&quot;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">m1</span><span class="o">.</span><span class="n">save</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">beatles</span><span class="o">.</span><span class="n">members</span><span class="o">.</span><span class="n">all</span><span class="p">()</span>
<span class="go">[&lt;Person: Ringo Starr&gt;]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">ringo</span><span class="o">.</span><span class="n">group_set</span><span class="o">.</span><span class="n">all</span><span class="p">()</span>
<span class="go">[&lt;Group: The Beatles&gt;]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">m2</span> <span class="o">=</span> <span class="n">Membership</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">create</span><span class="p">(</span><span class="n">person</span><span class="o">=</span><span class="n">paul</span><span class="p">,</span> <span class="n">group</span><span class="o">=</span><span class="n">beatles</span><span class="p">,</span>
<span class="gp">... </span>    <span class="n">date_joined</span><span class="o">=</span><span class="n">date</span><span class="p">(</span><span class="mi">1960</span><span class="p">,</span> <span class="mi">8</span><span class="p">,</span> <span class="mi">1</span><span class="p">),</span>
<span class="gp">... </span>    <span class="n">invite_reason</span><span class="o">=</span><span class="s">&quot;Wanted to form a band.&quot;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">beatles</span><span class="o">.</span><span class="n">members</span><span class="o">.</span><span class="n">all</span><span class="p">()</span>
<span class="go">[&lt;Person: Ringo Starr&gt;, &lt;Person: Paul McCartney&gt;]</span>
</pre></div>
</div>
<p>Unlike normal many-to-many fields, you <em>can&#8217;t</em> use <tt class="docutils literal"><span class="pre">add</span></tt>, <tt class="docutils literal"><span class="pre">create</span></tt>,
or assignment (i.e., <tt class="docutils literal"><span class="pre">beatles.members</span> <span class="pre">=</span> <span class="pre">[...]</span></tt>) to create relationships:</p>
<div class="highlight-python"><div class="highlight"><pre># THIS WILL NOT WORK
&gt;&gt;&gt; beatles.members.add(john)
# NEITHER WILL THIS
&gt;&gt;&gt; beatles.members.create(name=&quot;George Harrison&quot;)
# AND NEITHER WILL THIS
&gt;&gt;&gt; beatles.members = [john, paul, ringo, george]
</pre></div>
</div>
<p>Why? You can&#8217;t just create a relationship between a <tt class="docutils literal"><span class="pre">Person</span></tt> and a <tt class="docutils literal"><span class="pre">Group</span></tt>
- you need to specify all the detail for the relationship required by the
<tt class="docutils literal"><span class="pre">Membership</span></tt> model. The simple <tt class="docutils literal"><span class="pre">add</span></tt>, <tt class="docutils literal"><span class="pre">create</span></tt> and assignment calls
don&#8217;t provide a way to specify this extra detail. As a result, they are
disabled for many-to-many relationships that use an intermediate model.
The only way to create this type of relationship is to create instances of the
intermediate model.</p>
<p>The <a class="reference internal" href="../../ref/models/relations.html#django.db.models.fields.related.RelatedManager.remove" title="django.db.models.fields.related.RelatedManager.remove"><tt class="xref py py-meth docutils literal"><span class="pre">remove()</span></tt></a> method is
disabled for similar reasons. However, the
<a class="reference internal" href="../../ref/models/relations.html#django.db.models.fields.related.RelatedManager.clear" title="django.db.models.fields.related.RelatedManager.clear"><tt class="xref py py-meth docutils literal"><span class="pre">clear()</span></tt></a> method can be
used to remove all many-to-many relationships for an instance:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="c"># Beatles have broken up</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">beatles</span><span class="o">.</span><span class="n">members</span><span class="o">.</span><span class="n">clear</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="c"># Note that this deletes the intermediate model instances</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Membership</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">all</span><span class="p">()</span>
<span class="go">[]</span>
</pre></div>
</div>
<p>Once you have established the many-to-many relationships by creating instances
of your intermediate model, you can issue queries. Just as with normal
many-to-many relationships, you can query using the attributes of the
many-to-many-related model:</p>
<div class="highlight-python"><div class="highlight"><pre># Find all the groups with a member whose name starts with &#39;Paul&#39;
&gt;&gt;&gt; Group.objects.filter(members__name__startswith=&#39;Paul&#39;)
[&lt;Group: The Beatles&gt;]
</pre></div>
</div>
<p>As you are using an intermediate model, you can also query on its attributes:</p>
<div class="highlight-python"><div class="highlight"><pre># Find all the members of the Beatles that joined after 1 Jan 1961
&gt;&gt;&gt; Person.objects.filter(
...     group__name=&#39;The Beatles&#39;,
...     membership__date_joined__gt=date(1961,1,1))
[&lt;Person: Ringo Starr]
</pre></div>
</div>
<p>If you need to access a membership&#8217;s information you may do so by directly
querying the <tt class="docutils literal"><span class="pre">Membership</span></tt> model:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">ringos_membership</span> <span class="o">=</span> <span class="n">Membership</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="n">group</span><span class="o">=</span><span class="n">beatles</span><span class="p">,</span> <span class="n">person</span><span class="o">=</span><span class="n">ringo</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">ringos_membership</span><span class="o">.</span><span class="n">date_joined</span>
<span class="go">datetime.date(1962, 8, 16)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">ringos_membership</span><span class="o">.</span><span class="n">invite_reason</span>
<span class="go">u&#39;Needed a new drummer.&#39;</span>
</pre></div>
</div>
<p>Another way to access the same information is by querying the
<a class="reference internal" href="queries.html#m2m-reverse-relationships"><em>many-to-many reverse relationship</em></a> from a
<tt class="docutils literal"><span class="pre">Person</span></tt> object:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">ringos_membership</span> <span class="o">=</span> <span class="n">ringo</span><span class="o">.</span><span class="n">membership_set</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="n">group</span><span class="o">=</span><span class="n">beatles</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">ringos_membership</span><span class="o">.</span><span class="n">date_joined</span>
<span class="go">datetime.date(1962, 8, 16)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">ringos_membership</span><span class="o">.</span><span class="n">invite_reason</span>
<span class="go">u&#39;Needed a new drummer.&#39;</span>
</pre></div>
</div>
</div>
<div class="section" id="s-one-to-one-relationships">
<span id="one-to-one-relationships"></span><h4>One-to-one relationships<a class="headerlink" href="#one-to-one-relationships" title="Permalink to this headline">¶</a></h4>
<p>To define a one-to-one relationship, use
<a class="reference internal" href="../../ref/models/fields.html#django.db.models.OneToOneField" title="django.db.models.OneToOneField"><tt class="xref py py-class docutils literal"><span class="pre">OneToOneField</span></tt></a>. You use it just like any other
<tt class="docutils literal"><span class="pre">Field</span></tt> type: by including it as a class attribute of your model.</p>
<p>This is most useful on the primary key of an object when that object &#8220;extends&#8221;
another object in some way.</p>
<p><a class="reference internal" href="../../ref/models/fields.html#django.db.models.OneToOneField" title="django.db.models.OneToOneField"><tt class="xref py py-class docutils literal"><span class="pre">OneToOneField</span></tt></a> requires a positional argument: the
class to which the model is related.</p>
<p>For example, if you were building a database of &#8220;places&#8221;, you would
build pretty standard stuff such as address, phone number, etc. in the
database. Then, if you wanted to build a database of restaurants on
top of the places, instead of repeating yourself and replicating those
fields in the <tt class="docutils literal"><span class="pre">Restaurant</span></tt> model, you could make <tt class="docutils literal"><span class="pre">Restaurant</span></tt> have
a <a class="reference internal" href="../../ref/models/fields.html#django.db.models.OneToOneField" title="django.db.models.OneToOneField"><tt class="xref py py-class docutils literal"><span class="pre">OneToOneField</span></tt></a> to <tt class="docutils literal"><span class="pre">Place</span></tt> (because a
restaurant &#8220;is a&#8221; place; in fact, to handle this you&#8217;d typically use
<a class="reference internal" href="#model-inheritance"><em>inheritance</em></a>, which involves an implicit
one-to-one relation).</p>
<p>As with <a class="reference internal" href="../../ref/models/fields.html#django.db.models.ForeignKey" title="django.db.models.ForeignKey"><tt class="xref py py-class docutils literal"><span class="pre">ForeignKey</span></tt></a>, a
<a class="reference internal" href="../../ref/models/fields.html#recursive-relationships"><em>recursive relationship</em></a>
can be defined and
<a class="reference internal" href="../../ref/models/fields.html#lazy-relationships"><em>references to as-yet undefined models</em></a>
can be made; see <a class="reference internal" href="../../ref/models/fields.html#ref-onetoone"><em>the model field reference</em></a> for details.</p>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<p class="last">See the <a class="reference internal" href="examples/one_to_one.html"><em>One-to-one relationship model example</em></a> for a full example.</p>
</div>
<p><a class="reference internal" href="../../ref/models/fields.html#django.db.models.OneToOneField" title="django.db.models.OneToOneField"><tt class="xref py py-class docutils literal"><span class="pre">OneToOneField</span></tt></a> fields also accept one specific,
optional <tt class="docutils literal"><span class="pre">parent_link</span></tt> argument described in the <a class="reference internal" href="../../ref/models/fields.html#ref-onetoone"><em>model field
reference</em></a>.</p>
<p><a class="reference internal" href="../../ref/models/fields.html#django.db.models.OneToOneField" title="django.db.models.OneToOneField"><tt class="xref py py-class docutils literal"><span class="pre">OneToOneField</span></tt></a> classes used to automatically become
the primary key on a model. This is no longer true (although you can manually
pass in the <a class="reference internal" href="../../ref/models/fields.html#django.db.models.Field.primary_key" title="django.db.models.Field.primary_key"><tt class="xref py py-attr docutils literal"><span class="pre">primary_key</span></tt></a> argument if you like).
Thus, it&#8217;s now possible to have multiple fields of type
<a class="reference internal" href="../../ref/models/fields.html#django.db.models.OneToOneField" title="django.db.models.OneToOneField"><tt class="xref py py-class docutils literal"><span class="pre">OneToOneField</span></tt></a> on a single model.</p>
</div>
</div>
<div class="section" id="s-models-across-files">
<span id="models-across-files"></span><h3>Models across files<a class="headerlink" href="#models-across-files" title="Permalink to this headline">¶</a></h3>
<p>It&#8217;s perfectly OK to relate a model to one from another app. To do this, import
the related model at the top of the file where your model is defined. Then,
just refer to the other model class wherever needed. For example:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">from</span> <span class="nn">django.db</span> <span class="kn">import</span> <span class="n">models</span>
<span class="kn">from</span> <span class="nn">geography.models</span> <span class="kn">import</span> <span class="n">ZipCode</span>

<span class="k">class</span> <span class="nc">Restaurant</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span>
    <span class="c"># ...</span>
    <span class="n">zip_code</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">ForeignKey</span><span class="p">(</span><span class="n">ZipCode</span><span class="p">)</span>
</pre></div>
</div>
</div>
<div class="section" id="s-field-name-restrictions">
<span id="field-name-restrictions"></span><h3>Field name restrictions<a class="headerlink" href="#field-name-restrictions" title="Permalink to this headline">¶</a></h3>
<p>Django places only two restrictions on model field names:</p>
<ol class="arabic">
<li><p class="first">A field name cannot be a Python reserved word, because that would result
in a Python syntax error. For example:</p>
<div class="highlight-python"><div class="highlight"><pre>class Example(models.Model):
    pass = models.IntegerField() # &#39;pass&#39; is a reserved word!
</pre></div>
</div>
</li>
<li><p class="first">A field name cannot contain more than one underscore in a row, due to
the way Django&#8217;s query lookup syntax works. For example:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">class</span> <span class="nc">Example</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span>
    <span class="n">foo__bar</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">IntegerField</span><span class="p">()</span> <span class="c"># &#39;foo__bar&#39; has two underscores!</span>
</pre></div>
</div>
</li>
</ol>
<p>These limitations can be worked around, though, because your field name doesn&#8217;t
necessarily have to match your database column name. See the
<a class="reference internal" href="../../ref/models/fields.html#django.db.models.Field.db_column" title="django.db.models.Field.db_column"><tt class="xref py py-attr docutils literal"><span class="pre">db_column</span></tt></a> option.</p>
<p>SQL reserved words, such as <tt class="docutils literal"><span class="pre">join</span></tt>, <tt class="docutils literal"><span class="pre">where</span></tt> or <tt class="docutils literal"><span class="pre">select</span></tt>, <em>are</em> allowed as
model field names, because Django escapes all database table names and column
names in every underlying SQL query. It uses the quoting syntax of your
particular database engine.</p>
</div>
<div class="section" id="s-custom-field-types">
<span id="custom-field-types"></span><h3>Custom field types<a class="headerlink" href="#custom-field-types" title="Permalink to this headline">¶</a></h3>
<p>If one of the existing model fields cannot be used to fit your purposes, or if
you wish to take advantage of some less common database column types, you can
create your own field class. Full coverage of creating your own fields is
provided in <a class="reference internal" href="../../howto/custom-model-fields.html"><em>Writing custom model fields</em></a>.</p>
</div>
</div>
<div class="section" id="s-meta-options">
<span id="s-id3"></span><span id="meta-options"></span><span id="id3"></span><h2>Meta options<a class="headerlink" href="#meta-options" title="Permalink to this headline">¶</a></h2>
<p>Give your model metadata by using an inner <tt class="docutils literal"><span class="pre">class</span> <span class="pre">Meta</span></tt>, like so:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">from</span> <span class="nn">django.db</span> <span class="kn">import</span> <span class="n">models</span>

<span class="k">class</span> <span class="nc">Ox</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span>
    <span class="n">horn_length</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">IntegerField</span><span class="p">()</span>

    <span class="k">class</span> <span class="nc">Meta</span><span class="p">:</span>
        <span class="n">ordering</span> <span class="o">=</span> <span class="p">[</span><span class="s">&quot;horn_length&quot;</span><span class="p">]</span>
        <span class="n">verbose_name_plural</span> <span class="o">=</span> <span class="s">&quot;oxen&quot;</span>
</pre></div>
</div>
<p>Model metadata is &#8220;anything that&#8217;s not a field&#8221;, such as ordering options
(<a class="reference internal" href="../../ref/models/options.html#django.db.models.Options.ordering" title="django.db.models.Options.ordering"><tt class="xref py py-attr docutils literal"><span class="pre">ordering</span></tt></a>), database table name (<a class="reference internal" href="../../ref/models/options.html#django.db.models.Options.db_table" title="django.db.models.Options.db_table"><tt class="xref py py-attr docutils literal"><span class="pre">db_table</span></tt></a>), or
human-readable singular and plural names (<a class="reference internal" href="../../ref/models/options.html#django.db.models.Options.verbose_name" title="django.db.models.Options.verbose_name"><tt class="xref py py-attr docutils literal"><span class="pre">verbose_name</span></tt></a> and
<a class="reference internal" href="../../ref/models/options.html#django.db.models.Options.verbose_name_plural" title="django.db.models.Options.verbose_name_plural"><tt class="xref py py-attr docutils literal"><span class="pre">verbose_name_plural</span></tt></a>). None are required, and adding <tt class="docutils literal"><span class="pre">class</span>
<span class="pre">Meta</span></tt> to a model is completely optional.</p>
<p>A complete list of all possible <tt class="docutils literal"><span class="pre">Meta</span></tt> options can be found in the <a class="reference internal" href="../../ref/models/options.html"><em>model
option reference</em></a>.</p>
</div>
<div class="section" id="s-model-attributes">
<span id="s-id4"></span><span id="model-attributes"></span><span id="id4"></span><h2>Model attributes<a class="headerlink" href="#model-attributes" title="Permalink to this headline">¶</a></h2>
<dl class="docutils">
<dt><tt class="docutils literal"><span class="pre">objects</span></tt></dt>
<dd>The most important attribute of a model is the
<a class="reference internal" href="managers.html#django.db.models.Manager" title="django.db.models.Manager"><tt class="xref py py-class docutils literal"><span class="pre">Manager</span></tt></a>. It&#8217;s the interface through which
database query operations are provided to Django models and is used to
<a class="reference internal" href="queries.html#retrieving-objects"><em>retrieve the instances</em></a> from the database. If no
custom <tt class="docutils literal"><span class="pre">Manager</span></tt> is defined, the default name is <tt class="docutils literal"><span class="pre">objects</span></tt>. Managers
are only accessible via model classes, not the model instances.</dd>
</dl>
</div>
<div class="section" id="s-model-methods">
<span id="s-id5"></span><span id="model-methods"></span><span id="id5"></span><h2>Model methods<a class="headerlink" href="#model-methods" title="Permalink to this headline">¶</a></h2>
<p>Define custom methods on a model to add custom &#8220;row-level&#8221; functionality to your
objects. Whereas <a class="reference internal" href="managers.html#django.db.models.Manager" title="django.db.models.Manager"><tt class="xref py py-class docutils literal"><span class="pre">Manager</span></tt></a> methods are intended to do
&#8220;table-wide&#8221; things, model methods should act on a particular model instance.</p>
<p>This is a valuable technique for keeping business logic in one place &#8211; the
model.</p>
<p>For example, this model has a few custom methods:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">from</span> <span class="nn">django.db</span> <span class="kn">import</span> <span class="n">models</span>

<span class="k">class</span> <span class="nc">Person</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span>
    <span class="n">first_name</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">CharField</span><span class="p">(</span><span class="n">max_length</span><span class="o">=</span><span class="mi">50</span><span class="p">)</span>
    <span class="n">last_name</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">CharField</span><span class="p">(</span><span class="n">max_length</span><span class="o">=</span><span class="mi">50</span><span class="p">)</span>
    <span class="n">birth_date</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">DateField</span><span class="p">()</span>

    <span class="k">def</span> <span class="nf">baby_boomer_status</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="s">&quot;Returns the person&#39;s baby-boomer status.&quot;</span>
        <span class="kn">import</span> <span class="nn">datetime</span>
        <span class="k">if</span> <span class="bp">self</span><span class="o">.</span><span class="n">birth_date</span> <span class="o">&lt;</span> <span class="n">datetime</span><span class="o">.</span><span class="n">date</span><span class="p">(</span><span class="mi">1945</span><span class="p">,</span> <span class="mi">8</span><span class="p">,</span> <span class="mi">1</span><span class="p">):</span>
            <span class="k">return</span> <span class="s">&quot;Pre-boomer&quot;</span>
        <span class="k">elif</span> <span class="bp">self</span><span class="o">.</span><span class="n">birth_date</span> <span class="o">&lt;</span> <span class="n">datetime</span><span class="o">.</span><span class="n">date</span><span class="p">(</span><span class="mi">1965</span><span class="p">,</span> <span class="mi">1</span><span class="p">,</span> <span class="mi">1</span><span class="p">):</span>
            <span class="k">return</span> <span class="s">&quot;Baby boomer&quot;</span>
        <span class="k">else</span><span class="p">:</span>
            <span class="k">return</span> <span class="s">&quot;Post-boomer&quot;</span>

    <span class="k">def</span> <span class="nf">_get_full_name</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="s">&quot;Returns the person&#39;s full name.&quot;</span>
        <span class="k">return</span> <span class="s">&#39;</span><span class="si">%s</span><span class="s"> </span><span class="si">%s</span><span class="s">&#39;</span> <span class="o">%</span> <span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">first_name</span><span class="p">,</span> <span class="bp">self</span><span class="o">.</span><span class="n">last_name</span><span class="p">)</span>
    <span class="n">full_name</span> <span class="o">=</span> <span class="nb">property</span><span class="p">(</span><span class="n">_get_full_name</span><span class="p">)</span>
</pre></div>
</div>
<p>The last method in this example is a <a class="reference internal" href="../../glossary.html#term-property"><em class="xref std std-term">property</em></a>.</p>
<p>The <a class="reference internal" href="../../ref/models/instances.html"><em>model instance reference</em></a> has a complete list
of <a class="reference internal" href="../../ref/models/instances.html#model-instance-methods"><em>methods automatically given to each model</em></a>.
You can override most of these &#8211; see <a class="reference internal" href="#overriding-predefined-model-methods">overriding predefined model methods</a>,
below &#8211; but there are a couple that you&#8217;ll almost always want to define:</p>
<dl class="docutils">
<dt><a class="reference internal" href="../../ref/models/instances.html#django.db.models.Model.__str__" title="django.db.models.Model.__str__"><tt class="xref py py-meth docutils literal"><span class="pre">__str__()</span></tt></a> (Python 3)</dt>
<dd>Python 3 equivalent of <tt class="docutils literal"><span class="pre">__unicode__()</span></tt>.</dd>
<dt><a class="reference internal" href="../../ref/models/instances.html#django.db.models.Model.__unicode__" title="django.db.models.Model.__unicode__"><tt class="xref py py-meth docutils literal"><span class="pre">__unicode__()</span></tt></a> (Python 2)</dt>
<dd><p class="first">A Python &#8220;magic method&#8221; that returns a unicode &#8220;representation&#8221; of any
object. This is what Python and Django will use whenever a model
instance needs to be coerced and displayed as a plain string. Most
notably, this happens when you display an object in an interactive
console or in the admin.</p>
<p class="last">You&#8217;ll always want to define this method; the default isn&#8217;t very helpful
at all.</p>
</dd>
<dt><a class="reference internal" href="../../ref/models/instances.html#django.db.models.Model.get_absolute_url" title="django.db.models.Model.get_absolute_url"><tt class="xref py py-meth docutils literal"><span class="pre">get_absolute_url()</span></tt></a></dt>
<dd><p class="first">This tells Django how to calculate the URL for an object. Django uses
this in its admin interface, and any time it needs to figure out a URL
for an object.</p>
<p class="last">Any object that has a URL that uniquely identifies it should define this
method.</p>
</dd>
</dl>
<div class="section" id="s-overriding-predefined-model-methods">
<span id="s-overriding-model-methods"></span><span id="overriding-predefined-model-methods"></span><span id="overriding-model-methods"></span><h3>Overriding predefined model methods<a class="headerlink" href="#overriding-predefined-model-methods" title="Permalink to this headline">¶</a></h3>
<p>There&#8217;s another set of <a class="reference internal" href="../../ref/models/instances.html#model-instance-methods"><em>model methods</em></a> that
encapsulate a bunch of database behavior that you&#8217;ll want to customize. In
particular you&#8217;ll often want to change the way <a class="reference internal" href="../../ref/models/instances.html#django.db.models.Model.save" title="django.db.models.Model.save"><tt class="xref py py-meth docutils literal"><span class="pre">save()</span></tt></a> and
<a class="reference internal" href="../../ref/models/instances.html#django.db.models.Model.delete" title="django.db.models.Model.delete"><tt class="xref py py-meth docutils literal"><span class="pre">delete()</span></tt></a> work.</p>
<p>You&#8217;re free to override these methods (and any other model method) to alter
behavior.</p>
<p>A classic use-case for overriding the built-in methods is if you want something
to happen whenever you save an object. For example (see
<a class="reference internal" href="../../ref/models/instances.html#django.db.models.Model.save" title="django.db.models.Model.save"><tt class="xref py py-meth docutils literal"><span class="pre">save()</span></tt></a> for documentation of the parameters it accepts):</p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">from</span> <span class="nn">django.db</span> <span class="kn">import</span> <span class="n">models</span>

<span class="k">class</span> <span class="nc">Blog</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span>
    <span class="n">name</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">CharField</span><span class="p">(</span><span class="n">max_length</span><span class="o">=</span><span class="mi">100</span><span class="p">)</span>
    <span class="n">tagline</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">TextField</span><span class="p">()</span>

    <span class="k">def</span> <span class="nf">save</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">):</span>
        <span class="n">do_something</span><span class="p">()</span>
        <span class="nb">super</span><span class="p">(</span><span class="n">Blog</span><span class="p">,</span> <span class="bp">self</span><span class="p">)</span><span class="o">.</span><span class="n">save</span><span class="p">(</span><span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">)</span> <span class="c"># Call the &quot;real&quot; save() method.</span>
        <span class="n">do_something_else</span><span class="p">()</span>
</pre></div>
</div>
<p>You can also prevent saving:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">from</span> <span class="nn">django.db</span> <span class="kn">import</span> <span class="n">models</span>

<span class="k">class</span> <span class="nc">Blog</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span>
    <span class="n">name</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">CharField</span><span class="p">(</span><span class="n">max_length</span><span class="o">=</span><span class="mi">100</span><span class="p">)</span>
    <span class="n">tagline</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">TextField</span><span class="p">()</span>

    <span class="k">def</span> <span class="nf">save</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">):</span>
        <span class="k">if</span> <span class="bp">self</span><span class="o">.</span><span class="n">name</span> <span class="o">==</span> <span class="s">&quot;Yoko Ono&#39;s blog&quot;</span><span class="p">:</span>
            <span class="k">return</span> <span class="c"># Yoko shall never have her own blog!</span>
        <span class="k">else</span><span class="p">:</span>
            <span class="nb">super</span><span class="p">(</span><span class="n">Blog</span><span class="p">,</span> <span class="bp">self</span><span class="p">)</span><span class="o">.</span><span class="n">save</span><span class="p">(</span><span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">)</span> <span class="c"># Call the &quot;real&quot; save() method.</span>
</pre></div>
</div>
<p>It&#8217;s important to remember to call the superclass method &#8211; that&#8217;s
that <tt class="docutils literal"><span class="pre">super(Blog,</span> <span class="pre">self).save(*args,</span> <span class="pre">**kwargs)</span></tt> business &#8211; to ensure
that the object still gets saved into the database. If you forget to
call the superclass method, the default behavior won&#8217;t happen and the
database won&#8217;t get touched.</p>
<p>It&#8217;s also important that you pass through the arguments that can be
passed to the model method &#8211; that&#8217;s what the <tt class="docutils literal"><span class="pre">*args,</span> <span class="pre">**kwargs</span></tt> bit
does. Django will, from time to time, extend the capabilities of
built-in model methods, adding new arguments. If you use <tt class="docutils literal"><span class="pre">*args,</span>
<span class="pre">**kwargs</span></tt> in your method definitions, you are guaranteed that your
code will automatically support those arguments when they are added.</p>
<div class="admonition-overridden-model-methods-are-not-called-on-bulk-operations admonition">
<p class="first admonition-title">Overridden model methods are not called on bulk operations</p>
<p>Note that the <a class="reference internal" href="../../ref/models/instances.html#django.db.models.Model.delete" title="django.db.models.Model.delete"><tt class="xref py py-meth docutils literal"><span class="pre">delete()</span></tt></a> method for an object is not
necessarily called when <a class="reference internal" href="queries.html#topics-db-queries-delete"><em>deleting objects in bulk using a
QuerySet</em></a>. To ensure customized delete logic
gets executed, you can use <a class="reference internal" href="../../ref/signals.html#django.db.models.signals.pre_delete" title="django.db.models.signals.pre_delete"><tt class="xref py py-data docutils literal"><span class="pre">pre_delete</span></tt></a>
and/or <a class="reference internal" href="../../ref/signals.html#django.db.models.signals.post_delete" title="django.db.models.signals.post_delete"><tt class="xref py py-data docutils literal"><span class="pre">post_delete</span></tt></a> signals.</p>
<p class="last">Unfortunately, there isn&#8217;t a workaround when
<a class="reference internal" href="../../ref/models/querysets.html#django.db.models.query.QuerySet.bulk_create" title="django.db.models.query.QuerySet.bulk_create"><tt class="xref py py-meth docutils literal"><span class="pre">creating</span></tt></a> or
<a class="reference internal" href="../../ref/models/querysets.html#django.db.models.query.QuerySet.update" title="django.db.models.query.QuerySet.update"><tt class="xref py py-meth docutils literal"><span class="pre">updating</span></tt></a> objects in bulk,
since none of <a class="reference internal" href="../../ref/models/instances.html#django.db.models.Model.save" title="django.db.models.Model.save"><tt class="xref py py-meth docutils literal"><span class="pre">save()</span></tt></a>,
<a class="reference internal" href="../../ref/signals.html#django.db.models.signals.pre_save" title="django.db.models.signals.pre_save"><tt class="xref py py-data docutils literal"><span class="pre">pre_save</span></tt></a>, and
<a class="reference internal" href="../../ref/signals.html#django.db.models.signals.post_save" title="django.db.models.signals.post_save"><tt class="xref py py-data docutils literal"><span class="pre">post_save</span></tt></a> are called.</p>
</div>
</div>
<div class="section" id="s-executing-custom-sql">
<span id="executing-custom-sql"></span><h3>Executing custom SQL<a class="headerlink" href="#executing-custom-sql" title="Permalink to this headline">¶</a></h3>
<p>Another common pattern is writing custom SQL statements in model methods and
module-level methods. For more details on using raw SQL, see the documentation
on <a class="reference internal" href="sql.html"><em>using raw SQL</em></a>.</p>
</div>
</div>
<div class="section" id="s-model-inheritance">
<span id="s-id6"></span><span id="model-inheritance"></span><span id="id6"></span><h2>Model inheritance<a class="headerlink" href="#model-inheritance" title="Permalink to this headline">¶</a></h2>
<p>Model inheritance in Django works almost identically to the way normal
class inheritance works in Python, but the basics at the beginning of the page
should still be followed. That means the base class should subclass
<a class="reference internal" href="../../ref/models/instances.html#django.db.models.Model" title="django.db.models.Model"><tt class="xref py py-class docutils literal"><span class="pre">django.db.models.Model</span></tt></a>.</p>
<p>The only decision you have to make is whether you want the parent models to be
models in their own right (with their own database tables), or if the parents
are just holders of common information that will only be visible through the
child models.</p>
<p>There are three styles of inheritance that are possible in Django.</p>
<ol class="arabic simple">
<li>Often, you will just want to use the parent class to hold information that
you don&#8217;t want to have to type out for each child model. This class isn&#8217;t
going to ever be used in isolation, so <a class="reference internal" href="#abstract-base-classes"><em>Abstract base classes</em></a> are
what you&#8217;re after.</li>
<li>If you&#8217;re subclassing an existing model (perhaps something from another
application entirely) and want each model to have its own database table,
<a class="reference internal" href="#multi-table-inheritance"><em>Multi-table inheritance</em></a> is the way to go.</li>
<li>Finally, if you only want to modify the Python-level behavior of a model,
without changing the models fields in any way, you can use
<a class="reference internal" href="#proxy-models"><em>Proxy models</em></a>.</li>
</ol>
<div class="section" id="s-abstract-base-classes">
<span id="s-id7"></span><span id="abstract-base-classes"></span><span id="id7"></span><h3>Abstract base classes<a class="headerlink" href="#abstract-base-classes" title="Permalink to this headline">¶</a></h3>
<p>Abstract base classes are useful when you want to put some common
information into a number of other models. You write your base class
and put <tt class="docutils literal"><span class="pre">abstract=True</span></tt> in the <a class="reference internal" href="#meta-options"><em>Meta</em></a>
class. This model will then not be used to create any database
table. Instead, when it is used as a base class for other models, its
fields will be added to those of the child class. It is an error to
have fields in the abstract base class with the same name as those in
the child (and Django will raise an exception).</p>
<p>An example:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">from</span> <span class="nn">django.db</span> <span class="kn">import</span> <span class="n">models</span>

<span class="k">class</span> <span class="nc">CommonInfo</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span>
    <span class="n">name</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">CharField</span><span class="p">(</span><span class="n">max_length</span><span class="o">=</span><span class="mi">100</span><span class="p">)</span>
    <span class="n">age</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">PositiveIntegerField</span><span class="p">()</span>

    <span class="k">class</span> <span class="nc">Meta</span><span class="p">:</span>
        <span class="n">abstract</span> <span class="o">=</span> <span class="bp">True</span>

<span class="k">class</span> <span class="nc">Student</span><span class="p">(</span><span class="n">CommonInfo</span><span class="p">):</span>
    <span class="n">home_group</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">CharField</span><span class="p">(</span><span class="n">max_length</span><span class="o">=</span><span class="mi">5</span><span class="p">)</span>
</pre></div>
</div>
<p>The <tt class="docutils literal"><span class="pre">Student</span></tt> model will have three fields: <tt class="docutils literal"><span class="pre">name</span></tt>, <tt class="docutils literal"><span class="pre">age</span></tt> and
<tt class="docutils literal"><span class="pre">home_group</span></tt>. The <tt class="docutils literal"><span class="pre">CommonInfo</span></tt> model cannot be used as a normal Django
model, since it is an abstract base class. It does not generate a database
table or have a manager, and cannot be instantiated or saved directly.</p>
<p>For many uses, this type of model inheritance will be exactly what you want.
It provides a way to factor out common information at the Python level, whilst
still only creating one database table per child model at the database level.</p>
<div class="section" id="s-meta-inheritance">
<span id="meta-inheritance"></span><h4><tt class="docutils literal"><span class="pre">Meta</span></tt> inheritance<a class="headerlink" href="#meta-inheritance" title="Permalink to this headline">¶</a></h4>
<p>When an abstract base class is created, Django makes any <a class="reference internal" href="#meta-options"><em>Meta</em></a>
inner class you declared in the base class available as an
attribute. If a child class does not declare its own <a class="reference internal" href="#meta-options"><em>Meta</em></a>
class, it will inherit the parent&#8217;s <a class="reference internal" href="#meta-options"><em>Meta</em></a>. If the child wants to
extend the parent&#8217;s <a class="reference internal" href="#meta-options"><em>Meta</em></a> class, it can subclass it. For example:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">from</span> <span class="nn">django.db</span> <span class="kn">import</span> <span class="n">models</span>

<span class="k">class</span> <span class="nc">CommonInfo</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span>
    <span class="c"># ...</span>
    <span class="k">class</span> <span class="nc">Meta</span><span class="p">:</span>
        <span class="n">abstract</span> <span class="o">=</span> <span class="bp">True</span>
        <span class="n">ordering</span> <span class="o">=</span> <span class="p">[</span><span class="s">&#39;name&#39;</span><span class="p">]</span>

<span class="k">class</span> <span class="nc">Student</span><span class="p">(</span><span class="n">CommonInfo</span><span class="p">):</span>
    <span class="c"># ...</span>
    <span class="k">class</span> <span class="nc">Meta</span><span class="p">(</span><span class="n">CommonInfo</span><span class="o">.</span><span class="n">Meta</span><span class="p">):</span>
        <span class="n">db_table</span> <span class="o">=</span> <span class="s">&#39;student_info&#39;</span>
</pre></div>
</div>
<p>Django does make one adjustment to the <a class="reference internal" href="#meta-options"><em>Meta</em></a> class of an abstract base
class: before installing the <a class="reference internal" href="#meta-options"><em>Meta</em></a> attribute, it sets <tt class="docutils literal"><span class="pre">abstract=False</span></tt>.
This means that children of abstract base classes don&#8217;t automatically become
abstract classes themselves. Of course, you can make an abstract base class
that inherits from another abstract base class. You just need to remember to
explicitly set <tt class="docutils literal"><span class="pre">abstract=True</span></tt> each time.</p>
<p>Some attributes won&#8217;t make sense to include in the <a class="reference internal" href="#meta-options"><em>Meta</em></a> class of an
abstract base class. For example, including <tt class="docutils literal"><span class="pre">db_table</span></tt> would mean that all
the child classes (the ones that don&#8217;t specify their own <a class="reference internal" href="#meta-options"><em>Meta</em></a>) would use
the same database table, which is almost certainly not what you want.</p>
</div>
<div class="section" id="s-be-careful-with-related-name">
<span id="s-abstract-related-name"></span><span id="be-careful-with-related-name"></span><span id="abstract-related-name"></span><h4>Be careful with <tt class="docutils literal"><span class="pre">related_name</span></tt><a class="headerlink" href="#be-careful-with-related-name" title="Permalink to this headline">¶</a></h4>
<p>If you are using the <a class="reference internal" href="../../ref/models/fields.html#django.db.models.ForeignKey.related_name" title="django.db.models.ForeignKey.related_name"><tt class="xref py py-attr docutils literal"><span class="pre">related_name</span></tt></a> attribute on a <tt class="docutils literal"><span class="pre">ForeignKey</span></tt> or
<tt class="docutils literal"><span class="pre">ManyToManyField</span></tt>, you must always specify a <em>unique</em> reverse name for the
field. This would normally cause a problem in abstract base classes, since the
fields on this class are included into each of the child classes, with exactly
the same values for the attributes (including <a class="reference internal" href="../../ref/models/fields.html#django.db.models.ForeignKey.related_name" title="django.db.models.ForeignKey.related_name"><tt class="xref py py-attr docutils literal"><span class="pre">related_name</span></tt></a>) each time.</p>
<p>To work around this problem, when you are using <a class="reference internal" href="../../ref/models/fields.html#django.db.models.ForeignKey.related_name" title="django.db.models.ForeignKey.related_name"><tt class="xref py py-attr docutils literal"><span class="pre">related_name</span></tt></a> in an
abstract base class (only), part of the name should contain
<tt class="docutils literal"><span class="pre">'%(app_label)s'</span></tt> and <tt class="docutils literal"><span class="pre">'%(class)s'</span></tt>.</p>
<ul class="simple">
<li><tt class="docutils literal"><span class="pre">'%(class)s'</span></tt> is replaced by the lower-cased name of the child class
that the field is used in.</li>
<li><tt class="docutils literal"><span class="pre">'%(app_label)s'</span></tt> is replaced by the lower-cased name of the app the child
class is contained within. Each installed application name must be unique
and the model class names within each app must also be unique, therefore the
resulting name will end up being different.</li>
</ul>
<p>For example, given an app <tt class="docutils literal"><span class="pre">common/models.py</span></tt>:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">from</span> <span class="nn">django.db</span> <span class="kn">import</span> <span class="n">models</span>

<span class="k">class</span> <span class="nc">Base</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span>
    <span class="n">m2m</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">ManyToManyField</span><span class="p">(</span><span class="n">OtherModel</span><span class="p">,</span> <span class="n">related_name</span><span class="o">=</span><span class="s">&quot;</span><span class="si">%(app_label)s</span><span class="s">_</span><span class="si">%(class)s</span><span class="s">_related&quot;</span><span class="p">)</span>

    <span class="k">class</span> <span class="nc">Meta</span><span class="p">:</span>
        <span class="n">abstract</span> <span class="o">=</span> <span class="bp">True</span>

<span class="k">class</span> <span class="nc">ChildA</span><span class="p">(</span><span class="n">Base</span><span class="p">):</span>
    <span class="k">pass</span>

<span class="k">class</span> <span class="nc">ChildB</span><span class="p">(</span><span class="n">Base</span><span class="p">):</span>
    <span class="k">pass</span>
</pre></div>
</div>
<p>Along with another app <tt class="docutils literal"><span class="pre">rare/models.py</span></tt>:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">from</span> <span class="nn">common.models</span> <span class="kn">import</span> <span class="n">Base</span>

<span class="k">class</span> <span class="nc">ChildB</span><span class="p">(</span><span class="n">Base</span><span class="p">):</span>
    <span class="k">pass</span>
</pre></div>
</div>
<p>The reverse name of the <tt class="docutils literal"><span class="pre">common.ChildA.m2m</span></tt> field will be
<tt class="docutils literal"><span class="pre">common_childa_related</span></tt>, whilst the reverse name of the
<tt class="docutils literal"><span class="pre">common.ChildB.m2m</span></tt> field will be <tt class="docutils literal"><span class="pre">common_childb_related</span></tt>, and finally the
reverse name of the <tt class="docutils literal"><span class="pre">rare.ChildB.m2m</span></tt> field will be <tt class="docutils literal"><span class="pre">rare_childb_related</span></tt>.
It is up to you how you use the <tt class="docutils literal"><span class="pre">'%(class)s'</span></tt> and <tt class="docutils literal"><span class="pre">'%(app_label)s</span></tt> portion
to construct your related name, but if you forget to use it, Django will raise
errors when you perform system checks (or run <a class="reference internal" href="../../ref/django-admin.html#django-admin-migrate"><tt class="xref std std-djadmin docutils literal"><span class="pre">migrate</span></tt></a>).</p>
<p>If you don&#8217;t specify a <a class="reference internal" href="../../ref/models/fields.html#django.db.models.ForeignKey.related_name" title="django.db.models.ForeignKey.related_name"><tt class="xref py py-attr docutils literal"><span class="pre">related_name</span></tt></a>
attribute for a field in an abstract base class, the default reverse name will
be the name of the child class followed by <tt class="docutils literal"><span class="pre">'_set'</span></tt>, just as it normally
would be if you&#8217;d declared the field directly on the child class. For example,
in the above code, if the <a class="reference internal" href="../../ref/models/fields.html#django.db.models.ForeignKey.related_name" title="django.db.models.ForeignKey.related_name"><tt class="xref py py-attr docutils literal"><span class="pre">related_name</span></tt></a>
attribute was omitted, the reverse name for the <tt class="docutils literal"><span class="pre">m2m</span></tt> field would be
<tt class="docutils literal"><span class="pre">childa_set</span></tt> in the <tt class="docutils literal"><span class="pre">ChildA</span></tt> case and <tt class="docutils literal"><span class="pre">childb_set</span></tt> for the <tt class="docutils literal"><span class="pre">ChildB</span></tt>
field.</p>
</div>
</div>
<div class="section" id="s-multi-table-inheritance">
<span id="s-id8"></span><span id="multi-table-inheritance"></span><span id="id8"></span><h3>Multi-table inheritance<a class="headerlink" href="#multi-table-inheritance" title="Permalink to this headline">¶</a></h3>
<p>The second type of model inheritance supported by Django is when each model in
the hierarchy is a model all by itself. Each model corresponds to its own
database table and can be queried and created individually. The inheritance
relationship introduces links between the child model and each of its parents
(via an automatically-created <a class="reference internal" href="../../ref/models/fields.html#django.db.models.OneToOneField" title="django.db.models.OneToOneField"><tt class="xref py py-class docutils literal"><span class="pre">OneToOneField</span></tt></a>).
For example:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">from</span> <span class="nn">django.db</span> <span class="kn">import</span> <span class="n">models</span>

<span class="k">class</span> <span class="nc">Place</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span>
    <span class="n">name</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">CharField</span><span class="p">(</span><span class="n">max_length</span><span class="o">=</span><span class="mi">50</span><span class="p">)</span>
    <span class="n">address</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">CharField</span><span class="p">(</span><span class="n">max_length</span><span class="o">=</span><span class="mi">80</span><span class="p">)</span>

<span class="k">class</span> <span class="nc">Restaurant</span><span class="p">(</span><span class="n">Place</span><span class="p">):</span>
    <span class="n">serves_hot_dogs</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">BooleanField</span><span class="p">(</span><span class="n">default</span><span class="o">=</span><span class="bp">False</span><span class="p">)</span>
    <span class="n">serves_pizza</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">BooleanField</span><span class="p">(</span><span class="n">default</span><span class="o">=</span><span class="bp">False</span><span class="p">)</span>
</pre></div>
</div>
<p>All of the fields of <tt class="docutils literal"><span class="pre">Place</span></tt> will also be available in <tt class="docutils literal"><span class="pre">Restaurant</span></tt>,
although the data will reside in a different database table. So these are both
possible:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">Place</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">name</span><span class="o">=</span><span class="s">&quot;Bob&#39;s Cafe&quot;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Restaurant</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">name</span><span class="o">=</span><span class="s">&quot;Bob&#39;s Cafe&quot;</span><span class="p">)</span>
</pre></div>
</div>
<p>If you have a <tt class="docutils literal"><span class="pre">Place</span></tt> that is also a <tt class="docutils literal"><span class="pre">Restaurant</span></tt>, you can get from the
<tt class="docutils literal"><span class="pre">Place</span></tt> object to the <tt class="docutils literal"><span class="pre">Restaurant</span></tt> object by using the lower-case version
of the model name:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">p</span> <span class="o">=</span> <span class="n">Place</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="nb">id</span><span class="o">=</span><span class="mi">12</span><span class="p">)</span>
<span class="go"># If p is a Restaurant object, this will give the child class:</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">p</span><span class="o">.</span><span class="n">restaurant</span>
<span class="go">&lt;Restaurant: ...&gt;</span>
</pre></div>
</div>
<p>However, if <tt class="docutils literal"><span class="pre">p</span></tt> in the above example was <em>not</em> a <tt class="docutils literal"><span class="pre">Restaurant</span></tt> (it had been
created directly as a <tt class="docutils literal"><span class="pre">Place</span></tt> object or was the parent of some other class),
referring to <tt class="docutils literal"><span class="pre">p.restaurant</span></tt> would raise a <tt class="docutils literal"><span class="pre">Restaurant.DoesNotExist</span></tt>
exception.</p>
<div class="section" id="s-meta-and-multi-table-inheritance">
<span id="meta-and-multi-table-inheritance"></span><h4><tt class="docutils literal"><span class="pre">Meta</span></tt> and multi-table inheritance<a class="headerlink" href="#meta-and-multi-table-inheritance" title="Permalink to this headline">¶</a></h4>
<p>In the multi-table inheritance situation, it doesn&#8217;t make sense for a child
class to inherit from its parent&#8217;s <a class="reference internal" href="#meta-options"><em>Meta</em></a> class. All the <a class="reference internal" href="#meta-options"><em>Meta</em></a> options
have already been applied to the parent class and applying them again would
normally only lead to contradictory behavior (this is in contrast with the
abstract base class case, where the base class doesn&#8217;t exist in its own
right).</p>
<p>So a child model does not have access to its parent&#8217;s <a class="reference internal" href="#meta-options"><em>Meta</em></a> class. However, there are a few limited cases where the child
inherits behavior from the parent: if the child does not specify an
<a class="reference internal" href="../../ref/models/options.html#django.db.models.Options.ordering" title="django.db.models.Options.ordering"><tt class="xref py py-attr docutils literal"><span class="pre">ordering</span></tt></a> attribute or a
<a class="reference internal" href="../../ref/models/options.html#django.db.models.Options.get_latest_by" title="django.db.models.Options.get_latest_by"><tt class="xref py py-attr docutils literal"><span class="pre">get_latest_by</span></tt></a> attribute, it will inherit
these from its parent.</p>
<p>If the parent has an ordering and you don&#8217;t want the child to have any natural
ordering, you can explicitly disable it:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">class</span> <span class="nc">ChildModel</span><span class="p">(</span><span class="n">ParentModel</span><span class="p">):</span>
    <span class="c"># ...</span>
    <span class="k">class</span> <span class="nc">Meta</span><span class="p">:</span>
        <span class="c"># Remove parent&#39;s ordering effect</span>
        <span class="n">ordering</span> <span class="o">=</span> <span class="p">[]</span>
</pre></div>
</div>
</div>
<div class="section" id="s-inheritance-and-reverse-relations">
<span id="inheritance-and-reverse-relations"></span><h4>Inheritance and reverse relations<a class="headerlink" href="#inheritance-and-reverse-relations" title="Permalink to this headline">¶</a></h4>
<p>Because multi-table inheritance uses an implicit
<a class="reference internal" href="../../ref/models/fields.html#django.db.models.OneToOneField" title="django.db.models.OneToOneField"><tt class="xref py py-class docutils literal"><span class="pre">OneToOneField</span></tt></a> to link the child and
the parent, it&#8217;s possible to move from the parent down to the child,
as in the above example. However, this uses up the name that is the
default <a class="reference internal" href="../../ref/models/fields.html#django.db.models.ForeignKey.related_name" title="django.db.models.ForeignKey.related_name"><tt class="xref py py-attr docutils literal"><span class="pre">related_name</span></tt></a> value for
<a class="reference internal" href="../../ref/models/fields.html#django.db.models.ForeignKey" title="django.db.models.ForeignKey"><tt class="xref py py-class docutils literal"><span class="pre">ForeignKey</span></tt></a> and
<a class="reference internal" href="../../ref/models/fields.html#django.db.models.ManyToManyField" title="django.db.models.ManyToManyField"><tt class="xref py py-class docutils literal"><span class="pre">ManyToManyField</span></tt></a> relations.  If you
are putting those types of relations on a subclass of the parent model, you
<strong>must</strong> specify the <a class="reference internal" href="../../ref/models/fields.html#django.db.models.ForeignKey.related_name" title="django.db.models.ForeignKey.related_name"><tt class="xref py py-attr docutils literal"><span class="pre">related_name</span></tt></a>
attribute on each such field. If you forget, Django will raise a validation
error.</p>
<p>For example, using the above <tt class="docutils literal"><span class="pre">Place</span></tt> class again, let&#8217;s create another
subclass with a <a class="reference internal" href="../../ref/models/fields.html#django.db.models.ManyToManyField" title="django.db.models.ManyToManyField"><tt class="xref py py-class docutils literal"><span class="pre">ManyToManyField</span></tt></a>:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">class</span> <span class="nc">Supplier</span><span class="p">(</span><span class="n">Place</span><span class="p">):</span>
    <span class="n">customers</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">ManyToManyField</span><span class="p">(</span><span class="n">Place</span><span class="p">)</span>
</pre></div>
</div>
<p>This results in the error:</p>
<div class="highlight-python"><div class="highlight"><pre>Reverse query name for &#39;Supplier.customers&#39; clashes with reverse query
name for &#39;Supplier.place_ptr&#39;.

HINT: Add or change a related_name argument to the definition for
&#39;Supplier.customers&#39; or &#39;Supplier.place_ptr&#39;.
</pre></div>
</div>
<p>Adding <tt class="docutils literal"><span class="pre">related_name</span></tt> to the <tt class="docutils literal"><span class="pre">customers</span></tt> field as follows would resolve the
error: <tt class="docutils literal"><span class="pre">models.ManyToManyField(Place,</span> <span class="pre">related_name='provider')</span></tt>.</p>
</div>
<div class="section" id="s-specifying-the-parent-link-field">
<span id="specifying-the-parent-link-field"></span><h4>Specifying the parent link field<a class="headerlink" href="#specifying-the-parent-link-field" title="Permalink to this headline">¶</a></h4>
<p>As mentioned, Django will automatically create a
<a class="reference internal" href="../../ref/models/fields.html#django.db.models.OneToOneField" title="django.db.models.OneToOneField"><tt class="xref py py-class docutils literal"><span class="pre">OneToOneField</span></tt></a> linking your child
class back any non-abstract parent models. If you want to control the
name of the attribute linking back to the parent, you can create your
own <a class="reference internal" href="../../ref/models/fields.html#django.db.models.OneToOneField" title="django.db.models.OneToOneField"><tt class="xref py py-class docutils literal"><span class="pre">OneToOneField</span></tt></a> and set
<a class="reference internal" href="../../ref/models/fields.html#django.db.models.OneToOneField.parent_link" title="django.db.models.OneToOneField.parent_link"><tt class="xref py py-attr docutils literal"><span class="pre">parent_link=True</span></tt></a>
to indicate that your field is the link back to the parent class.</p>
</div>
</div>
<div class="section" id="s-proxy-models">
<span id="s-id9"></span><span id="proxy-models"></span><span id="id9"></span><h3>Proxy models<a class="headerlink" href="#proxy-models" title="Permalink to this headline">¶</a></h3>
<p>When using <a class="reference internal" href="#multi-table-inheritance"><em>multi-table inheritance</em></a>, a new
database table is created for each subclass of a model. This is usually the
desired behavior, since the subclass needs a place to store any additional
data fields that are not present on the base class. Sometimes, however, you
only want to change the Python behavior of a model &#8211; perhaps to change the
default manager, or add a new method.</p>
<p>This is what proxy model inheritance is for: creating a <em>proxy</em> for the
original model. You can create, delete and update instances of the proxy model
and all the data will be saved as if you were using the original (non-proxied)
model. The difference is that you can change things like the default model
ordering or the default manager in the proxy, without having to alter the
original.</p>
<p>Proxy models are declared like normal models. You tell Django that it&#8217;s a
proxy model by setting the <a class="reference internal" href="../../ref/models/options.html#django.db.models.Options.proxy" title="django.db.models.Options.proxy"><tt class="xref py py-attr docutils literal"><span class="pre">proxy</span></tt></a> attribute of
the <tt class="docutils literal"><span class="pre">Meta</span></tt> class to <tt class="docutils literal"><span class="pre">True</span></tt>.</p>
<p>For example, suppose you want to add a method to the <tt class="docutils literal"><span class="pre">Person</span></tt> model. You can do it like this:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">from</span> <span class="nn">django.db</span> <span class="kn">import</span> <span class="n">models</span>

<span class="k">class</span> <span class="nc">Person</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span>
    <span class="n">first_name</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">CharField</span><span class="p">(</span><span class="n">max_length</span><span class="o">=</span><span class="mi">30</span><span class="p">)</span>
    <span class="n">last_name</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">CharField</span><span class="p">(</span><span class="n">max_length</span><span class="o">=</span><span class="mi">30</span><span class="p">)</span>

<span class="k">class</span> <span class="nc">MyPerson</span><span class="p">(</span><span class="n">Person</span><span class="p">):</span>
    <span class="k">class</span> <span class="nc">Meta</span><span class="p">:</span>
        <span class="n">proxy</span> <span class="o">=</span> <span class="bp">True</span>

    <span class="k">def</span> <span class="nf">do_something</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="c"># ...</span>
        <span class="k">pass</span>
</pre></div>
</div>
<p>The <tt class="docutils literal"><span class="pre">MyPerson</span></tt> class operates on the same database table as its parent
<tt class="docutils literal"><span class="pre">Person</span></tt> class. In particular, any new instances of <tt class="docutils literal"><span class="pre">Person</span></tt> will also be
accessible through <tt class="docutils literal"><span class="pre">MyPerson</span></tt>, and vice-versa:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">p</span> <span class="o">=</span> <span class="n">Person</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">create</span><span class="p">(</span><span class="n">first_name</span><span class="o">=</span><span class="s">&quot;foobar&quot;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">MyPerson</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="n">first_name</span><span class="o">=</span><span class="s">&quot;foobar&quot;</span><span class="p">)</span>
<span class="go">&lt;MyPerson: foobar&gt;</span>
</pre></div>
</div>
<p>You could also use a proxy model to define a different default ordering on
a model. You might not always want to order the <tt class="docutils literal"><span class="pre">Person</span></tt> model, but regularly
order by the <tt class="docutils literal"><span class="pre">last_name</span></tt> attribute when you use the proxy. This is easy:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">class</span> <span class="nc">OrderedPerson</span><span class="p">(</span><span class="n">Person</span><span class="p">):</span>
    <span class="k">class</span> <span class="nc">Meta</span><span class="p">:</span>
        <span class="n">ordering</span> <span class="o">=</span> <span class="p">[</span><span class="s">&quot;last_name&quot;</span><span class="p">]</span>
        <span class="n">proxy</span> <span class="o">=</span> <span class="bp">True</span>
</pre></div>
</div>
<p>Now normal <tt class="docutils literal"><span class="pre">Person</span></tt> queries will be unordered
and <tt class="docutils literal"><span class="pre">OrderedPerson</span></tt> queries will be ordered by <tt class="docutils literal"><span class="pre">last_name</span></tt>.</p>
<div class="section" id="s-querysets-still-return-the-model-that-was-requested">
<span id="querysets-still-return-the-model-that-was-requested"></span><h4>QuerySets still return the model that was requested<a class="headerlink" href="#querysets-still-return-the-model-that-was-requested" title="Permalink to this headline">¶</a></h4>
<p>There is no way to have Django return, say, a <tt class="docutils literal"><span class="pre">MyPerson</span></tt> object whenever you
query for <tt class="docutils literal"><span class="pre">Person</span></tt> objects. A queryset for <tt class="docutils literal"><span class="pre">Person</span></tt> objects will return
those types of objects. The whole point of proxy objects is that code relying
on the original <tt class="docutils literal"><span class="pre">Person</span></tt> will use those and your own code can use the
extensions you included (that no other code is relying on anyway). It is not
a way to replace the <tt class="docutils literal"><span class="pre">Person</span></tt> (or any other) model everywhere with something
of your own creation.</p>
</div>
<div class="section" id="s-base-class-restrictions">
<span id="base-class-restrictions"></span><h4>Base class restrictions<a class="headerlink" href="#base-class-restrictions" title="Permalink to this headline">¶</a></h4>
<p>A proxy model must inherit from exactly one non-abstract model class. You
can&#8217;t inherit from multiple non-abstract models as the proxy model doesn&#8217;t
provide any connection between the rows in the different database tables. A
proxy model can inherit from any number of abstract model classes, providing
they do <em>not</em> define any model fields.</p>
<p>Proxy models inherit any <tt class="docutils literal"><span class="pre">Meta</span></tt> options that they don&#8217;t define from their
non-abstract model parent (the model they are proxying for).</p>
</div>
<div class="section" id="s-proxy-model-managers">
<span id="proxy-model-managers"></span><h4>Proxy model managers<a class="headerlink" href="#proxy-model-managers" title="Permalink to this headline">¶</a></h4>
<p>If you don&#8217;t specify any model managers on a proxy model, it inherits the
managers from its model parents. If you define a manager on the proxy model,
it will become the default, although any managers defined on the parent
classes will still be available.</p>
<p>Continuing our example from above, you could change the default manager used
when you query the <tt class="docutils literal"><span class="pre">Person</span></tt> model like this:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">from</span> <span class="nn">django.db</span> <span class="kn">import</span> <span class="n">models</span>

<span class="k">class</span> <span class="nc">NewManager</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Manager</span><span class="p">):</span>
    <span class="c"># ...</span>
    <span class="k">pass</span>

<span class="k">class</span> <span class="nc">MyPerson</span><span class="p">(</span><span class="n">Person</span><span class="p">):</span>
    <span class="n">objects</span> <span class="o">=</span> <span class="n">NewManager</span><span class="p">()</span>

    <span class="k">class</span> <span class="nc">Meta</span><span class="p">:</span>
        <span class="n">proxy</span> <span class="o">=</span> <span class="bp">True</span>
</pre></div>
</div>
<p>If you wanted to add a new manager to the Proxy, without replacing the
existing default, you can use the techniques described in the <a class="reference internal" href="managers.html#custom-managers-and-inheritance"><em>custom
manager</em></a> documentation: create a base class
containing the new managers and inherit that after the primary base class:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="c"># Create an abstract class for the new manager.</span>
<span class="k">class</span> <span class="nc">ExtraManagers</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span>
    <span class="n">secondary</span> <span class="o">=</span> <span class="n">NewManager</span><span class="p">()</span>

    <span class="k">class</span> <span class="nc">Meta</span><span class="p">:</span>
        <span class="n">abstract</span> <span class="o">=</span> <span class="bp">True</span>

<span class="k">class</span> <span class="nc">MyPerson</span><span class="p">(</span><span class="n">Person</span><span class="p">,</span> <span class="n">ExtraManagers</span><span class="p">):</span>
    <span class="k">class</span> <span class="nc">Meta</span><span class="p">:</span>
        <span class="n">proxy</span> <span class="o">=</span> <span class="bp">True</span>
</pre></div>
</div>
<p>You probably won&#8217;t need to do this very often, but, when you do, it&#8217;s
possible.</p>
</div>
<div class="section" id="s-differences-between-proxy-inheritance-and-unmanaged-models">
<span id="s-proxy-vs-unmanaged-models"></span><span id="differences-between-proxy-inheritance-and-unmanaged-models"></span><span id="proxy-vs-unmanaged-models"></span><h4>Differences between proxy inheritance and  unmanaged models<a class="headerlink" href="#differences-between-proxy-inheritance-and-unmanaged-models" title="Permalink to this headline">¶</a></h4>
<p>Proxy model inheritance might look fairly similar to creating an unmanaged
model, using the <a class="reference internal" href="../../ref/models/options.html#django.db.models.Options.managed" title="django.db.models.Options.managed"><tt class="xref py py-attr docutils literal"><span class="pre">managed</span></tt></a> attribute on a
model&#8217;s <tt class="docutils literal"><span class="pre">Meta</span></tt> class. The two alternatives are not quite the same and it&#8217;s
worth considering which one you should use.</p>
<p>One difference is that you can (and, in fact, must unless you want an empty
model) specify model fields on models with <tt class="docutils literal"><span class="pre">Meta.managed=False</span></tt>. You could,
with careful setting of <a class="reference internal" href="../../ref/models/options.html#django.db.models.Options.db_table" title="django.db.models.Options.db_table"><tt class="xref py py-attr docutils literal"><span class="pre">Meta.db_table</span></tt></a> create an unmanaged model that shadowed
an existing model and add Python methods to it. However, that would be very
repetitive and fragile as you need to keep both copies synchronized if you
make any changes.</p>
<p>The other difference that is more important for proxy models, is how model
managers are handled. Proxy models are intended to behave exactly like the
model they are proxying for. So they inherit the parent model&#8217;s managers,
including the default manager. In the normal multi-table model inheritance
case, children do not inherit managers from their parents as the custom
managers aren&#8217;t always appropriate when extra fields are involved. The
<a class="reference internal" href="managers.html#custom-managers-and-inheritance"><em>manager documentation</em></a> has more
details about this latter case.</p>
<p>When these two features were implemented, attempts were made to squash them
into a single option. It turned out that interactions with inheritance, in
general, and managers, in particular, made the API very complicated and
potentially difficult to understand and use. It turned out that two options
were needed in any case, so the current separation arose.</p>
<p>So, the general rules are:</p>
<ol class="arabic simple">
<li>If you are mirroring an existing model or database table and don&#8217;t want
all the original database table columns, use <tt class="docutils literal"><span class="pre">Meta.managed=False</span></tt>.
That option is normally useful for modeling database views and tables
not under the control of Django.</li>
<li>If you are wanting to change the Python-only behavior of a model, but
keep all the same fields as in the original, use <tt class="docutils literal"><span class="pre">Meta.proxy=True</span></tt>.
This sets things up so that the proxy model is an exact copy of the
storage structure of the original model when data is saved.</li>
</ol>
</div>
</div>
<div class="section" id="s-multiple-inheritance">
<span id="s-model-multiple-inheritance-topic"></span><span id="multiple-inheritance"></span><span id="model-multiple-inheritance-topic"></span><h3>Multiple inheritance<a class="headerlink" href="#multiple-inheritance" title="Permalink to this headline">¶</a></h3>
<p>Just as with Python&#8217;s subclassing, it&#8217;s possible for a Django model to inherit
from multiple parent models. Keep in mind that normal Python name resolution
rules apply. The first base class that a particular name (e.g. <a class="reference internal" href="#meta-options"><em>Meta</em></a>) appears in will be the one that is used; for example, this
means that if multiple parents contain a <a class="reference internal" href="#meta-options"><em>Meta</em></a> class,
only the first one is going to be used, and all others will be ignored.</p>
<p>Generally, you won&#8217;t need to inherit from multiple parents. The main use-case
where this is useful is for &#8220;mix-in&#8221; classes: adding a particular extra
field or method to every class that inherits the mix-in. Try to keep your
inheritance hierarchies as simple and straightforward as possible so that you
won&#8217;t have to struggle to work out where a particular piece of information is
coming from.</p>
<div class="versionchanged">
<span class="title">Changed in Django 1.7.</span> </div>
<p>Before Django 1.7, inheriting from multiple models that had an <tt class="docutils literal"><span class="pre">id</span></tt> primary
key field did not raise an error, but could result in data loss. For example,
consider these models (which no longer validate due to the clashing <tt class="docutils literal"><span class="pre">id</span></tt>
fields):</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">class</span> <span class="nc">Article</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span>
    <span class="n">headline</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">CharField</span><span class="p">(</span><span class="n">max_length</span><span class="o">=</span><span class="mi">50</span><span class="p">)</span>
    <span class="n">body</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">TextField</span><span class="p">()</span>

<span class="k">class</span> <span class="nc">Book</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span>
    <span class="n">title</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">CharField</span><span class="p">(</span><span class="n">max_length</span><span class="o">=</span><span class="mi">50</span><span class="p">)</span>

<span class="k">class</span> <span class="nc">BookReview</span><span class="p">(</span><span class="n">Book</span><span class="p">,</span> <span class="n">Article</span><span class="p">):</span>
    <span class="k">pass</span>
</pre></div>
</div>
<p>This snippet demonstrates how creating a child object overwrote the value of a
previously created parent object:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">article</span> <span class="o">=</span> <span class="n">Article</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">create</span><span class="p">(</span><span class="n">headline</span><span class="o">=</span><span class="s">&#39;Some piece of news.&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">review</span> <span class="o">=</span> <span class="n">BookReview</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">create</span><span class="p">(</span>
<span class="gp">... </span>    <span class="n">headline</span><span class="o">=</span><span class="s">&#39;Review of Little Red Riding Hood.&#39;</span><span class="p">,</span>
<span class="gp">... </span>    <span class="n">title</span><span class="o">=</span><span class="s">&#39;Little Red Riding Hood&#39;</span><span class="p">)</span>
<span class="go">&gt;&gt;&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">assert</span> <span class="n">Article</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="n">pk</span><span class="o">=</span><span class="n">article</span><span class="o">.</span><span class="n">pk</span><span class="p">)</span><span class="o">.</span><span class="n">headline</span> <span class="o">==</span> <span class="n">article</span><span class="o">.</span><span class="n">headline</span>
<span class="gt">Traceback (most recent call last):</span>
  File <span class="nb">&quot;&lt;console&gt;&quot;</span>, line <span class="m">1</span>, in <span class="n">&lt;module&gt;</span>
<span class="gr">AssertionError</span>
<span class="gp">&gt;&gt;&gt; </span><span class="c"># the &quot;Some piece of news.&quot; headline has been overwritten.</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Article</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="n">pk</span><span class="o">=</span><span class="n">article</span><span class="o">.</span><span class="n">pk</span><span class="p">)</span><span class="o">.</span><span class="n">headline</span>
<span class="go">&#39;Review of Little Red Riding Hood.&#39;</span>
</pre></div>
</div>
<p>To properly use multiple inheritance, you can use an explicit
<a class="reference internal" href="../../ref/models/fields.html#django.db.models.AutoField" title="django.db.models.AutoField"><tt class="xref py py-class docutils literal"><span class="pre">AutoField</span></tt></a> in the base models:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">class</span> <span class="nc">Article</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span>
    <span class="n">article_id</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">AutoField</span><span class="p">(</span><span class="n">primary_key</span><span class="o">=</span><span class="bp">True</span><span class="p">)</span>
    <span class="o">...</span>

<span class="k">class</span> <span class="nc">Book</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span>
    <span class="n">book_id</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">AutoField</span><span class="p">(</span><span class="n">primary_key</span><span class="o">=</span><span class="bp">True</span><span class="p">)</span>
    <span class="o">...</span>

<span class="k">class</span> <span class="nc">BookReview</span><span class="p">(</span><span class="n">Book</span><span class="p">,</span> <span class="n">Article</span><span class="p">):</span>
    <span class="k">pass</span>
</pre></div>
</div>
<p>Or use a common ancestor to hold the <a class="reference internal" href="../../ref/models/fields.html#django.db.models.AutoField" title="django.db.models.AutoField"><tt class="xref py py-class docutils literal"><span class="pre">AutoField</span></tt></a>:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">class</span> <span class="nc">Piece</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span>
    <span class="k">pass</span>

<span class="k">class</span> <span class="nc">Article</span><span class="p">(</span><span class="n">Piece</span><span class="p">):</span>
    <span class="o">...</span>

<span class="k">class</span> <span class="nc">Book</span><span class="p">(</span><span class="n">Piece</span><span class="p">):</span>
    <span class="o">...</span>

<span class="k">class</span> <span class="nc">BookReview</span><span class="p">(</span><span class="n">Book</span><span class="p">,</span> <span class="n">Article</span><span class="p">):</span>
    <span class="k">pass</span>
</pre></div>
</div>
</div>
<div class="section" id="s-field-name-hiding-is-not-permitted">
<span id="field-name-hiding-is-not-permitted"></span><h3>Field name &#8220;hiding&#8221; is not permitted<a class="headerlink" href="#field-name-hiding-is-not-permitted" title="Permalink to this headline">¶</a></h3>
<p>In normal Python class inheritance, it is permissible for a child class to
override any attribute from the parent class. In Django, this is not permitted
for attributes that are <a class="reference internal" href="../../ref/models/fields.html#django.db.models.Field" title="django.db.models.Field"><tt class="xref py py-class docutils literal"><span class="pre">Field</span></tt></a> instances (at
least, not at the moment). If a base class has a field called <tt class="docutils literal"><span class="pre">author</span></tt>, you
cannot create another model field called <tt class="docutils literal"><span class="pre">author</span></tt> in any class that inherits
from that base class.</p>
<p>Overriding fields in a parent model leads to difficulties in areas such as
initializing new instances (specifying which field is being initialized in
<tt class="docutils literal"><span class="pre">Model.__init__</span></tt>) and serialization. These are features which normal Python
class inheritance doesn&#8217;t have to deal with in quite the same way, so the
difference between Django model inheritance and Python class inheritance isn&#8217;t
arbitrary.</p>
<p>This restriction only applies to attributes which are
<a class="reference internal" href="../../ref/models/fields.html#django.db.models.Field" title="django.db.models.Field"><tt class="xref py py-class docutils literal"><span class="pre">Field</span></tt></a> instances. Normal Python attributes
can be overridden if you wish. It also only applies to the name of the
attribute as Python sees it: if you are manually specifying the database
column name, you can have the same column name appearing in both a child and
an ancestor model for multi-table inheritance (they are columns in two
different database tables).</p>
<p>Django will raise a <a class="reference internal" href="../../ref/exceptions.html#django.core.exceptions.FieldError" title="django.core.exceptions.FieldError"><tt class="xref py py-exc docutils literal"><span class="pre">FieldError</span></tt></a> if you override
any model field in any ancestor model.</p>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt><a class="reference internal" href="../../ref/models/index.html"><em>The Models Reference</em></a></dt>
<dd>Covers all the model related APIs including model fields, related
objects, and <tt class="docutils literal"><span class="pre">QuerySet</span></tt>.</dd>
</dl>
</div>
</div>
</div>
</div>


          </div>
        </div>
      </div>
      
        
          <div class="yui-b" id="sidebar">
            
      <div class="sphinxsidebar">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">Models</a><ul>
<li><a class="reference internal" href="#quick-example">Quick example</a></li>
<li><a class="reference internal" href="#using-models">Using models</a></li>
<li><a class="reference internal" href="#fields">Fields</a><ul>
<li><a class="reference internal" href="#field-types">Field types</a></li>
<li><a class="reference internal" href="#field-options">Field options</a></li>
<li><a class="reference internal" href="#automatic-primary-key-fields">Automatic primary key fields</a></li>
<li><a class="reference internal" href="#verbose-field-names">Verbose field names</a></li>
<li><a class="reference internal" href="#relationships">Relationships</a><ul>
<li><a class="reference internal" href="#many-to-one-relationships">Many-to-one relationships</a></li>
<li><a class="reference internal" href="#many-to-many-relationships">Many-to-many relationships</a></li>
<li><a class="reference internal" href="#extra-fields-on-many-to-many-relationships">Extra fields on many-to-many relationships</a></li>
<li><a class="reference internal" href="#one-to-one-relationships">One-to-one relationships</a></li>
</ul>
</li>
<li><a class="reference internal" href="#models-across-files">Models across files</a></li>
<li><a class="reference internal" href="#field-name-restrictions">Field name restrictions</a></li>
<li><a class="reference internal" href="#custom-field-types">Custom field types</a></li>
</ul>
</li>
<li><a class="reference internal" href="#meta-options">Meta options</a></li>
<li><a class="reference internal" href="#model-attributes">Model attributes</a></li>
<li><a class="reference internal" href="#model-methods">Model methods</a><ul>
<li><a class="reference internal" href="#overriding-predefined-model-methods">Overriding predefined model methods</a></li>
<li><a class="reference internal" href="#executing-custom-sql">Executing custom SQL</a></li>
</ul>
</li>
<li><a class="reference internal" href="#model-inheritance">Model inheritance</a><ul>
<li><a class="reference internal" href="#abstract-base-classes">Abstract base classes</a><ul>
<li><a class="reference internal" href="#meta-inheritance"><tt class="docutils literal"><span class="pre">Meta</span></tt> inheritance</a></li>
<li><a class="reference internal" href="#be-careful-with-related-name">Be careful with <tt class="docutils literal"><span class="pre">related_name</span></tt></a></li>
</ul>
</li>
<li><a class="reference internal" href="#multi-table-inheritance">Multi-table inheritance</a><ul>
<li><a class="reference internal" href="#meta-and-multi-table-inheritance"><tt class="docutils literal"><span class="pre">Meta</span></tt> and multi-table inheritance</a></li>
<li><a class="reference internal" href="#inheritance-and-reverse-relations">Inheritance and reverse relations</a></li>
<li><a class="reference internal" href="#specifying-the-parent-link-field">Specifying the parent link field</a></li>
</ul>
</li>
<li><a class="reference internal" href="#proxy-models">Proxy models</a><ul>
<li><a class="reference internal" href="#querysets-still-return-the-model-that-was-requested">QuerySets still return the model that was requested</a></li>
<li><a class="reference internal" href="#base-class-restrictions">Base class restrictions</a></li>
<li><a class="reference internal" href="#proxy-model-managers">Proxy model managers</a></li>
<li><a class="reference internal" href="#differences-between-proxy-inheritance-and-unmanaged-models">Differences between proxy inheritance and  unmanaged models</a></li>
</ul>
</li>
<li><a class="reference internal" href="#multiple-inheritance">Multiple inheritance</a></li>
<li><a class="reference internal" href="#field-name-hiding-is-not-permitted">Field name &#8220;hiding&#8221; is not permitted</a></li>
</ul>
</li>
</ul>
</li>
</ul>

  <h3>Browse</h3>
  <ul>
    
      <li>Prev: <a href="index.html">Models and databases</a></li>
    
    
      <li>Next: <a href="queries.html">Making queries</a></li>
    
  </ul>
  <h3>You are here:</h3>
  <ul>
      <li>
        <a href="../../index.html">Django 1.7.8.dev20150401230226 documentation</a>
        
          <ul><li><a href="../index.html">Using Django</a>
        
          <ul><li><a href="index.html">Models and databases</a>
        
        <ul><li>Models</li></ul>
        </li></ul></li></ul>
      </li>
  </ul>

  <h3>This Page</h3>
  <ul class="this-page-menu">
    <li><a href="../../_sources/topics/db/models.txt"
           rel="nofollow">Show Source</a></li>
  </ul>
<div id="searchbox" style="display: none">
  <h3>Quick search</h3>
    <form class="search" action="../../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    <p class="searchtip" style="font-size: 90%">
    Enter search terms or a module, class or function name.
    </p>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
              <h3>Last update:</h3>
              <p class="topless">Apr 02, 2015</p>
          </div>
        
      
    </div>

    <div id="ft">
      <div class="nav">
    &laquo; <a href="index.html" title="Models and databases">previous</a>
     |
    <a href="../index.html" title="Using Django" accesskey="U">up</a>
   |
    <a href="queries.html" title="Making queries">next</a> &raquo;</div>
    </div>
  </div>

      <div class="clearer"></div>
    </div>
  </body>
</html>